简体   繁体   中英

Java Scanner Error: Exception in thread “main” java.util.NoSuchElementException

I just started my university course in java and keep getting this error with the Scanner class.

import java.util.Scanner;

public class InchConversion
{
    public static void main (String[] args)
    {   
        Double inches, centimeters;
        Scanner fromKeyboard = new Scanner(System.in);
        System.out.println("Enter Value in Inches");
        inches = fromKeyboard.nextDouble();
        centimeters = inches*2.54;
        System.out. println(inches + " inches is equal to " + centimeters + " centimeters.");
    }
}

and the error I keep getting is:

  Compiling InchConversion.java.......
-----------OUTPUT-----------
Enter Value in Inches
Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1485)
    at java.util.Scanner.nextDouble(Scanner.java:2413)
    at InchConversion.main(InchConversion.java:11)
[Finished in 0.8s with exit code 1]

You need to use 3.0 for the input for example, because you explicitely tell the scanner to expect float value, and in Java float needs the decimal, even if it is whole number. Workouround would be:

double inches = Double.parseDouble(fromKeyboard.nextLine());

This way you tell the scanner to parse first String value on current line that can also be interpreted as double(in this case the java compiler does not care even if the number has no decimal, it adds it during the parsing process). So if you enter 20, it will automaticall add decimal and inches = 20.0 . But if you want inches = 20.1 you still have to enter 20dot1. But at least it gets rid of unintuitive and alien 20.0 input.

EDIT: I tried your code with my fix and it works perfectly fine for me

public static void main (String[] args) {   
    Double inches, centimeters;
    Scanner fromKeyboard = new Scanner(System.in);
    System.out.println("Enter Value in Inches");
    inches = Double.parseDouble(fromKeyboard.nextLine());
    centimeters = inches*2.54;
    System.out.println(inches + " inches is equal to " + centimeters + " centimeters.");
}

The output if you enter 1 is 1.0 inches is equal to 2.54 centimeters.

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