从扫描仪输入 Java 接收浮点数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29856140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Receiving float from Scanner input Java
提问by Kala
I need a method that should check whether user's input is a float, and if it is string or int it should throw an exception.
我需要一个方法来检查用户的输入是否是一个浮点数,如果它是字符串或整数,它应该抛出一个异常。
I declare the Scanner outside of the method:
我在方法之外声明了 Scanner:
Scanner sc = new Scanner(System.in);
And the method definition is:
方法定义是:
private boolean CheckFloat(Scanner sc) throws MyException {
if(!sc.hasNextFloat()){
throw new MyException("Wrong type");
}
else {
float input = sc.nextFloat();
if(input%1==0) {
throw new MyException("Wrong type");
}
else return true;
}
}
The problem is that the exception is thrown no matter what the user types in, so my question is: what exactly do I do wrong?
问题是无论用户输入什么都会抛出异常,所以我的问题是:我到底做错了什么?
I know that in Java an input like 1.2 is interpreted as double, but how to take a float from the console then? Or do I misunderstand working of the method hasNextFloat() or the whole Scanner?
我知道在 Java 中,像 1.2 这样的输入被解释为 double,但是如何从控制台获取浮点数呢?还是我误解了方法 hasNextFloat() 或整个 Scanner 的工作原理?
I haven't found anything helpful so far
到目前为止我还没有发现任何有用的东西
采纳答案by Shar1er80
Since you're using nextFloat()
you must be sure that you enter a floating number, otherwise clear the scanner with next()
由于您正在使用,nextFloat()
您必须确保输入一个浮点数,否则用next()
public static void main(String[] args) throws Exception {
while (true) {
System.out.print("Enter a float: ");
try {
float myFloat = input.nextFloat();
if (myFloat % 1 == 0) {
throw new Exception("Wrong type");
}
System.out.println(myFloat);
} catch (InputMismatchException ime) {
System.out.println(ime.toString());
input.next(); // Flush the buffer from all data
}
}
}
Results:
结果:
UPDATE
更新
You still have to handle the InputMismatchException, just throw your own exception in the catch block.
您仍然必须处理 InputMismatchException,只需在 catch 块中抛出您自己的异常即可。
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// while (true) just for testing
while (true) {
try {
System.out.print("Enter a float: ");
System.out.println(CheckFloat(input));
} catch (MyException me) {
System.out.println(me.toString());
}
}
}
private static float CheckFloat(Scanner sc) throws MyException {
try {
float input = sc.nextFloat();
if (input % 1 == 0) {
throw new MyException("Wrong type");
} else {
return input;
}
} catch (InputMismatchException ime) {
sc.next(); // Flush the scanner
// Rethrow your own exception
throw new MyException("Wrong type");
}
}
private static class MyException extends Exception {
// You exception details
public MyException(String message) {
super(message);
}
}
Results:
结果: