0
Why this code not working here and throw NoSuchElementException?
import java.util.Scanner; public class Program { public static void main(String[] args) { Scanner in=new Scanner(System.in); System.out.println("Insert Number"); while(!in.hasNextInt()){ System.out.println("Invalid Input"); System.out.println("Insert Number"); in.next(); } in.nextInt(); } }
1 Answer
+ 2
your problem is that you call in.next() inside your while(!in.hasNextInt()).
itÂŽs like you want to eat an apple but there are no apples left.
a possible solution e.g.:
is import java.util.Scanner;
public class Program {
public static void main(String[] args) {
System.out.println("Insert Number");
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
String text = String.valueOf(in.nextInt());
System.err.println(text);
}
}
}