简体   繁体   中英

Java Error - “Exception in thread ”main" java.util.NoSuchElementException

I am taking an introductory class in programming with Java, so please excuse my ignorance when it comes to programming concepts/terminology. Part of my current assignment is to read an integer number (corresponding to length, in inches) and to convert it to centimeters, printing the final converted number as a floating point value. However, I always get an error message when trying to run the project (in Eclipse) that says:

Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at project1.inches(project1.java:82)
    at project1.main(project1.java:17)

I have looked over my code several times, but can't seem to find out what the problem is -- Can anybody help me figure out how to fix this? I will include a snippet of the source code below:

public static void inches() {
    //Define object variables
    int vinch;
    float vcent;

    System.out.println("\n*******************************************************\n");
    System.out.println("Inch to Centimeter Conversion\n\n------------------------\n");

    //Read length (inches)
    System.out.println("Enter a length (in inches):");
    Scanner scanInches = new Scanner(System.in);
    vinch = scanInches.nextInt();

    //Convert input from inches to centimeters & print as float value
    vcent = (float) (vinch * 2.84);
    System.out.println(vinch + " inches is equal to " + vcent + " centimeters.");

    scanInches.close();
}

Thanks for your help and once again, I apologize for such a trivial question!

**Note: I'm sure my code has errors or impracticalities in it...feel free to point these out, should you find any.

You do not want to close System.in

  // scanInches.close();  comment this out

Also you should test for the presence of an int using

if (scanInches.hasNextInt())
    vinch = scanInches.nextInt();

I don't seem to see any error when I run the code. Here is the code, I just tested it to see if it runs correctly and it does, I made only a few changes.

public class Main {

    public static void main(String[] args) {
        inches();
    }

    public static void inches() {
        //Define object variables
        int vinch = 0;
        float vcent;

        System.out.println("\n*******************************************************\n");
        System.out.println("Inch to Centimeter Conversion\n\n------------------------\n");

        //Read length (inches)
        System.out.println("Enter a length (in inches):");
        Scanner scanInches = new Scanner(System.in);

        if (scanInches.hasNextInt())
        {
            vinch = scanInches.nextInt();
        }

        //Convert input from inches to centimeters & print as float value
        vcent = (float) (vinch * 2.54);
        System.out.println(vinch + " inches is equal to " + vcent + " centimeters.");

    }
}

As you can see I removed the scanner close method from the bottom of the inches method as you don't want to close it. I also added a check to see if there was nextInt to grab from the input of the user just to be safe. Also according to google, the conversion rate is 2.54, not 2.84 so I changed that too.

Let's dissect the error message the runtime helpfully provided:

Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at project1.inches(project1.java:82)

This means that your code, on line 82 of project1.java, invoked the method java.util.Scanner.nextInt(), which signaled an error condition by throwing a java.util.NoSuchElementException.

To figure out why the method throws this exception, let's read its documentation :

public int nextInt()

Scans the next token of the input as an int.

An invocation of this method of the form nextInt() behaves in exactly the same way as the invocation nextInt(radix), where radix is the default radix of this scanner.

Returns:

the int scanned from the input

Throws:

InputMismatchException - if the next token does not match the Integer regular expression, or is out of range

NoSuchElementException - if input is exhausted

IllegalStateException - if this scanner is closed

Therefore, a NoSuchElementException indicates that you tried to read another number, but System.in was exhausted.

That's weird, because System.in is usually connected to the keyboard, which provides an inexhaustible supply of keypresses ...

The most likely cause is therefore that you launched the program without a console, which is a setting in your launch configuration:

分配控制台复选框

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