如何检查用户输入的数据类型有效性(Java Scanner类)

我试图创建一个简单的UI,要求用户输入双类型数字,如果他们的输入不是双重类型,程序应该保持打印提示,直到用户输入有效的双重类型。 我的下面的代码还没有完全正常工作,因为当用户键入有效的double类型时,除非用户键入另一个double类型号,否则程序不会执行任何操作。 我想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? 

由于您可能无法输入双精度数,因此最好在String中读取,然后尝试将其转换为double。 标准模式是:

 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"); } } 

在输入double之前,循环不能退出,之后userInput将保存该值。

另请注意如何通过将提示放在循环中,可以避免无效输入上的代码重复。

您的代码非常完美: 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); 

对于此输入:

 test test int 49,5 23.4 

得到:

 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 

哪个是正确的,因为49,5不是十进制数,因为它使用了错误的分隔符。

对于int和double,我会这样做的方式是舍入并检查它是否仍然相同。

 double input = sc.nextdouble(); if(input == Math.floor(input) { //Double } else { //Int } 

这是一种检查输入是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"); } } } } 

那么Double.parseDouble(stringInput); 当您将输入扫描为String时,您可以解析它以查看它是否为double。 但是,如果在try-catch语句中包装此静态方法调用,则可以处理未解析double值的情况。

我认为你的代码没有工作的原因是因为它首先会检查给定的输入是double类型还是不是( sc.hasNextDouble() )如果没有再接受输入( sc.hasNext() …没有使用这个line),然后你再次输入( userInput = sc.nextDouble()

我建议这样做:

 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(); 

如果你是第一次提供双输入,你需要再次给出输入,我想如果你有任何时候你给双输入然后你必须再次提供它,它似乎不可能只提供一次输入。