如何检查用户输入的数据类型有效性(Java Scanner 类)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18817826/
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
how to check the data type validity of user's input (Java Scanner class)
提问by TonyGW
I am trying to make a simple UI that asks users to input double-type numbers, if theirs input is not of double type, the program should keep printing the prompt until user inputs a valid double type. My code below is not quite working yet, because when a user types in a valid double type, the program does not do anything unless the user types another double type number. I guess the condition (sc.hasNextDouble()) in the while loop consumes the first valid input. How to correct this? thanks a lot
我正在尝试制作一个简单的用户界面,要求用户输入双类型数字,如果他们的输入不是双类型,程序应该继续打印提示,直到用户输入有效的双类型。我下面的代码还不能正常工作,因为当用户输入有效的双精度类型时,除非用户输入另一个双类型数字,否则程序不会执行任何操作。我猜 while 循环中的条件 (sc.hasNextDouble()) 消耗了第一个有效输入。如何纠正这个?多谢
Scanner sc = new Scanner(System.in);
System.out.println("Type a double-type number:");
while (!sc.hasNextDouble())
{
System.out.println("Invalid input\n Type the double-type number:");
sc.next();
}
userInput = sc.nextDouble(); // need to check the data type?
回答by Chris
The way I would do it, for int vs. double would be to round and check if its still the same..
我会这样做,对于 int 与 double 将是四舍五入并检查它是否仍然相同..
double input = sc.nextdouble();
if(input == Math.floor(input) {
//Double
} else {
//Int
}
Here is a way to check if the input is an Int, Double, String, or Character
这是一种检查输入是否为 Int、Double、String 或 Character 的方法
import java.util.Scanner;
public class Variables {
/**
* @param args
*/
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = scan.next();
try{
double isNum = Double.parseDouble(input);
if(isNum == Math.floor(isNum)) {
System.out.println("Input is Integer");
}else {
System.out.println("Input is Double");
}
} catch(Exception e) {
if(input.toCharArray().length == 1) {
System.out.println("Input is Character");
}else {
System.out.println("Input is String");
}
}
}
}
回答by blackpanther
What about Double.parseDouble(stringInput);
when you scan the input as a String you can then parse it to see if it is a double. But, if you wrap this static method call in a try-catch statement, then you can handle the situation where a double value is not parsed.
怎么样 Double.parseDouble(stringInput);
,当你扫描输入的字符串然后你可以分析它,看它是否是一个双。但是,如果将此静态方法调用包装在 try-catch 语句中,则可以处理未解析双精度值的情况。
回答by Martijn Courteaux
Your code works perfect: http://ideone.com/NN42UGand http://ideone.com/MVbjMz
您的代码完美运行:http: //ideone.com/NN42UG和http://ideone.com/MVbjMz
Scanner sc = new Scanner(System.in);
System.out.println("Type a double-type number:");
while (!sc.hasNextDouble())
{
System.out.println("Invalid input\n Type the double-type number:");
sc.next();
}
double userInput = sc.nextDouble(); // need to check the data type?
System.out.println("Here it is: " + userInput);
For this input:
对于此输入:
test test
int
49,5
23.4
Gives:
给出:
Type a double-type number:
Invalid input
Type the double-type number:
Invalid input
Type the double-type number:
Invalid input
Type the double-type number:
Invalid input
Type the double-type number:
Here it is: 23.4
Which is correct, since 49,5
is not a decimal number because it uses the wrong separator.
这是正确的,因为49,5
它不是十进制数,因为它使用了错误的分隔符。
回答by Bohemian
Since you may notget a double entered, best to read in a String, then attempt to convert it to a double. The standard pattern is:
由于您可能无法输入双精度值,因此最好读入字符串,然后尝试将其转换为双精度值。标准模式是:
Scanner sc = new Scanner(System.in);
double userInput = 0;
while (true) {
System.out.println("Type a double-type number:");
try {
userInput = Double.parseDouble(sc.next());
break; // will only get to here if input was a double
} catch (NumberFormatException ignore) {
System.out.println("Invalid input");
}
}
The loop can't exit until a double has been entered, after which userInput
will hold that value.
在输入双精度值之前,循环无法退出,之后userInput
将保持该值。
Note also how by putting the prompt inside the loop, you can avoid code duplication on invalid input.
还要注意如何通过将提示放入循环中,可以避免无效输入上的代码重复。
回答by Aman Vikram Singh
I think the reason your code is not working due to first it will check the given input is of type double or not(sc.hasNextDouble()
) if not then take again input(sc.hasNext()
... no use of this line),then again you are taking input (userInput = sc.nextDouble()
)
我认为您的代码无法正常工作的原因是首先它会检查给定的输入类型为 double 或 not( sc.hasNextDouble()
) 如果不是,则再次输入(sc.hasNext()
...不使用此行),然后再次输入(userInput = sc.nextDouble()
)
I would suggest to do like this:
我建议这样做:
Scanner sc = new Scanner(System.in);
System.out.println("Type a double-type number:");
double userinput;
while (!sc.hasNextDouble())
{
System.out.println("Invalid input\n Type the double-type number:");
}
userInput = sc.nextDouble();
you need to give the input again if you are providing double input at first time,i think if any time you give double input then you have to provide it again ,it looks to impossible to provide input only one time.
如果您第一次提供双重输入,则需要再次提供输入,我认为如果任何时候您提供双重输入,那么您必须再次提供它,似乎不可能只提供一次输入。