简体   繁体   中英

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:

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):

Thrown by the nextElement method of an Enumeration to indicate that there are no more elements in the enumeration.

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.

You have not declared the variable input in your code. and for taking string input write something like this,

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(); 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 .

NoSuchElementException is thrown when there are no more available tokens. You have to call hasNext() to correct your program.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM