[英]Java Exception in thread java.util.NoSuchElementException
I have a java app source code, and it gets an error same as app that I write code here. 我有一个Java应用程序源代码,它得到的错误与我在此处编写代码的应用程序相同。 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.
他们两个都得到这个:“线程” main“中的异常” java.util.NoSuchElementException“如果我解决了这个问题,那么我可以在我的主要Java应用程序中解决问题。
When I run this java app, it run once, and when back to do-while loop, it gets error. 当我运行此Java应用程序时,它将运行一次,而回到do-while循环时,它将出错。 " Exception in thread "main" java.util.NoSuchElementException "
“线程” 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. 您将在
sum()
和sub()
的末尾关闭Scanner
,您不应该这样做。 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. 发生的事情是
Scanner#close()
方法也关闭了基础输入流,因此下一次通过主循环System.in
已关闭,从而导致异常。
I think that you should open your Scanner once for all 我认为您应该一次打开扫描仪
Good luck 祝好运
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.