为什么Java在使用Scanner.nextFloat()而不是Scanner.nextInt()时会抛出错误?
package myshit;
import java.lang.Math;
import java.util.Scanner;
public class speed2 {
public static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args){
float number = keyboard.nextFloat();
System.out.print("Start");
}
}
输入:
2.5
输出:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextFloat(Unknown Source)
at myshit.speed2.main(speed2.java:10)
但是只需将nextFloat切换到nextInt就不会发生错误:
package myshit;
import java.lang.Math;
import java.util.Scanner;
public class speed2 {
public static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args){
int number = keyboard.nextInt();
System.out.print("Start");
}
}
输入:
3
输出:
Start
我做错了什么?
出现我需要输入,而不是。 似乎是因为Eclipse
答案 0 :(得分:2)
你应该输入2,5而不是2.5(我认为这只发生在Netbeans,有趣的事实是它被解析为2.5)
run:
2,5
Your number is 2.5
在Netbeans中使用符号2.5。
run:
2.5
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextFloat(Scanner.java:2345)
at test.Test.main(Test.java:25)
答案 1 :(得分:0)
我希望你不要试图从命令行给一个浮点数输入2.5f
...因为那时你得到一个错误..
除了你的代码工作正常,你可以看到你是否添加打印你输入的数字:
import java.lang.Math;
import java.util.Scanner;
public class speed2 {
public static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args){
System.out.print("Give me float:");
float number = keyboard.nextFloat();
System.out.print("You gave me the number: " + number);
}
}
输出
Give me float:2.5
You gave me the number: 2.5