NoSuchElementException for nextInt

compiling below code gives an error, can someone help me in resolving this?

import java.util.;
import java.lang.
;
import java.io.*;
import java.util.Scanner;

/* Name of the class has to be “Main” only if the class is public. */

class Codechef

{

public static void main (String[] args) 

{ 

    int a,b; 

    Scanner input = new Scanner(System.in);

    a=input.nextInt(); 

    b=input.nextInt(); 

        int diff = 0, output1 = 0, output2 = 0, diffDigits =0; 

    diff = a-b; 

} 

}

just give proper inputs and run it… U wont get any error :slight_smile:
JAVA yells when it doesn’t get required inputs…

import java.util.*;

import java.lang.*;

import java.io.*;

class Codechef

{

public static void main (String[] args)

{

int a,b;

Scanner input = new Scanner(System.in);

a=input.nextInt();

b=input.nextInt();

System.out.println(a-b);

}

}

above code is still giving below error and NZEC as Runtime error

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 Codechef.main(Main.java:11) 

Read my answer… Give inputs to compiler and error will vanish… and you are getting wrong answer because your logic is incorrect…

Try using BufferedReader. Worked out fine for me. A scenario you have to keep in mind is if the user enters NULL value i.e. simply presses enter. In that case you should surround your input in a Try block, while Catch just returns.

Ex :

try
{cases = Integer.parseInt(br.readLine());}
catch(Exception e)
{return;}

//