NoSuchElementException for nextInt

Yes, this eliminates the errors caused by nextInt().
Now the code works fine.

There is no error in logic. NoSuchElementException comes because when nextInt() method is searching for next int, there is no next int found.
The way to resolve this is:
while(scanner.hasNextInt()){
int num1 = sc.nextInt();
}
Try using this for taking input.

2 Likes

@msn2106 thanks this works for me :smiley:

use hasNext() before inputting to resolve that error.

surround your code with Try and Catch it will work fine

/* package codechef; // don’t place package name! */

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

/* Name of the class has to be “Main” only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner sc = new Scanner(System.in);
int num=0;

	while(true)
	{
	    
	    try{
	    num=sc.nextInt(); 
	    if(num!=42)
	        System.out.println(num);
	    else
	    break;
	    }
	    catch(Exception e)
	    {
	        return;
	    }
	}
}

}

it is working fine

1 Like

Thank you bro … it worked … i wasted so much time facing this error … Tq

1 Like

Thanks Brother. Your code snipper helped me resolve the error. Keep up the good work.

It passes all the test cases I give. But when I press run to open test cases it fails, same for in python and c++.

surround the whole input thing in try - catch block; where catch just returns.

try{
int t = ob.nextInt();
         [whole body of program]
}catch(Exception E){
return;
}


I also had a similar error, your recommendations were helpful.