[英]Error Exception in thread “main” java.util.NoSuchElementException
I wrote is very simple calculator in Java, but I've got a problem in this code: 我用Java写了一个非常简单的计算器,但是这段代码有一个问题:
import java.util.Scanner;
public class Operation extends Declaration {
public static void main(String[] args){
int w = 0;
Scanner scan=new Scanner(System.in);
for(int i=0;i<1;){
System.out.println("WYBIERZ RODZAJ DZIALANIA: ");
System.out.println("1- DODAWANIE");
System.out.println("2- ODEJMOWANIE");
System.out.println("3- MNOZENIE");
System.out.println("4- DZIELENIE");
input=scan.next();
if(validate(input)){
m = Integer.parseInt(input);
if(m > 0 && m < 5){
i++;
} else {
System.out.println("Podaj liczbe w zakresie 1-4. ");
}
}
else{
System.out.println("Niestety, podana wartosc nie jest liczba calkowita. ");
}
}
}
}
Unfortunately I'm getting an error: 不幸的是我遇到一个错误:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at Operation.main(Operation.java:15)
at Calculator.main(Calculator.java:5)
Please help. 请帮忙。
The error message says it: 错误消息说:
Exception in thread "main" java.util.NoSuchElementException
..
at java.util.Scanner.next(Unknown Source)
If we read the documentation of the Exception , it states (bold emphasis of mine): 如果我们阅读Exception的文档 ,它会指出(我的粗体):
Thrown by the nextElement method of an Enumeration to indicate that there are no more elements in the enumeration.
由 Enumeration 的nextElement方法抛出,以指示该枚举中没有更多元素 。
If we assume that input has been declared correctly, the error is still in this line: 如果我们假设输入已正确声明,则错误仍在此行中:
input=scan.next();
There is no next element. 没有下一个元素。 Call hasNext() before, to make sure that there actually is a next element.
之前调用hasNext(),以确保确实存在下一个元素。
You have not declared the variable input in your code. 您尚未在代码中声明变量输入。 and for taking string
input
write something like this, 对于字符串
input
编写如下内容,
String input=scan.nextLine();
for taking integer as an input write: 用于将整数作为输入写入:
int input=scan.nextInt();
where scan is your Scanner object 扫描是您的扫描仪对象
The line 15 in the Operation class is: input=scan.next();
Operation类中的第15行是:
input=scan.next();
The documentation page for that method, assuming that the variable was declared (you would have had a compilation error otherwise) is: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next%28%29 . 假设已声明变量(否则将发生编译错误),则该方法的文档页面为: http : //docs.oracle.com/javase/7/docs/api/java/util/Scanner.html #next%28%29 。
NoSuchElementException is thrown when there are no more available tokens. 没有更多可用令牌时,将引发NoSuchElementException。 You have to call
hasNext()
to correct your program. 您必须调用
hasNext()
来更正您的程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.