Error related problem

my code is below:

Scanner scn= new Scanner(System.in);
int sum = 0;

        while(sum >= 0){

            int n = scn.nextInt();
            sum += n;

            if(sum < 0) break;
            System.out.println(n);
        }

Why I am getting this error in coding block IDE:

Exception in thread “main” java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Main.main(Main.java:9)

it basically means the element u r requesting does not exist
you need to check if the next input exists then only go in the while loop
use scn.hasNext(),it ll pass all the test cases
your corrected code:

import java.util.*;
public class Main {
public static void main(String args[]) {

    Scanner scn = new Scanner(System.in);
    int sum = 0;

    while(sum >= 0&& scn.hasNext()){

        int n = scn.nextInt();
        sum += n;

        if(sum < 0) break;
        System.out.println(n);
    }
}
}

this solves your doubt please mark it as resolved :slight_smile: