I have a java app source code, and it gets an error same as app that I write code here. both of them get this: " Exception in thread "main" java.util.NoSuchElementException " if I fix this, then I can fix the problem in my primary java app.
When I run this java app, it run once, and when back to do-while loop, it gets error. " Exception in thread "main" java.util.NoSuchElementException "
Code:
public static void main (String args[]) {
int c=-1;
Scanner input=new Scanner(System.in);
do{
System.out.println("1- Sum");
System.out.println("2- Sub");
System.out.print("Enter your selection : > ");
c=input.nextInt();
res(c);
}while(c!=0);
input.close();
}
public static void res(int c) {
switch (c) {
case 1:
System.out.println("++++++++++");
sum();
break;
case 2:
System.out.println("----------");
sub();
break;
default:
break;
}
}
public static void sum() {
float a,b,c;
Scanner in=new Scanner(System.in);
System.out.println("enter two number :");
System.out.print("first number : ");
a=in.nextInt();
System.out.print("second number : ");
b=in.nextInt();
c=a+b;
System.out.println(a+" + "+b+" = "+c+" END.");
in.close();
}
public static void sub() {
float a,b,c;
Scanner in=new Scanner(System.in);
System.out.println("enter two number :");
System.out.print("first number : ");
a=in.nextInt();
System.out.print("second number : ");
b=in.nextInt();
c=a-b;
System.out.println(a+" - "+b+" = "+c+" END.");
in.close();
}
Does anyone can help me to fix this?
You are closing the Scanner
at the end of sum()
and sub()
, which you should not be doing. Remove those two statements and the problem should be fixed.
What is happening is that the Scanner#close()
method closes the underlying input stream as well, so the next time through the main loop System.in
has been closed, causing the exception.
I think that you should open your Scanner once for all
Good luck
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.