我刚开始使用java开始我的大学课程,并继续使用Scanner课程出现此错误。
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.");
}
}
我不断得到的错误是:
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]
答案 0 :(得分:4)
例如,您需要使用3.0作为输入,因为您明确地告诉扫描器期望浮点值,并且在Java float中需要小数,即使它是整数。 Workouround将是:
double inches = Double.parseDouble(fromKeyboard.nextLine());
这样你告诉扫描器解析当前行上的第一个字符串值,也可以解释为double(在这种情况下,即使数字没有小数,java编译器也不关心,它在解析过程中添加它) 。因此,如果输入20,它将自动添加小数和inches = 20.0
。但是如果你想要inches = 20.1
,你仍然需要输入20dot1。但至少它摆脱了不直观的外星人20.0输入。
编辑:我用我的修复程序尝试了你的代码,它对我来说非常好
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.");
}
如果输入1,则输出为1.0 inches is equal to 2.54 centimeters.