输入验证检查输入是否为双精度

时间:2019-02-15 16:36:07

标签: java validation input try-catch

我想检查我输入的输入是否正确的数据类型。例如,如果用户在我希望他们输入int时输入double,则程序将告诉他们有错误。这是我到目前为止的内容:

System.out.println("Enter the temperature in double:");
String temp = input.nextLine();
try
{
    Double temperature = Double.parseDouble(temp);
}
catch(Exception e)
{
    isValid = false;
    System.out.println("Temperature  must be a double ");
}

它的所有工作正在继续执行,并且在我输入int时未打印出错误消息。在此问题上停留了一段时间,因此将不胜感激。

2 个答案:

答案 0 :(得分:1)

我认为您希望仅验证十进制数字(不包括整数)。在这种情况下,您可以使用 regex 进行相同操作:

System.out.println("Enter the temperature in double:");
String temp = input.nextLine();
while (temp != null && !temp.matches("^[0-9]*\\.([0-9]+)+$")) {       // use of regex here
    System.out.println("Enter the temperature in double:");
    temp = input.nextLine();                                          // read input again
}

这将循环直到用户只输入有效的十进制输入。 this regex 的说明。

答案 1 :(得分:0)

由于您不希望import pandas as pd new_df = pd.DataFrame(df.values.tolist(), index= df.index, columns=["C", "D"]) # this is the output A C D 1 [1] [2] 2 [1, 2] [3, 4] 3 [1, 2, 3, 4] [6, 7, 8, 9]] 被接受,因此只需添加int来检查输入if是否具有小数点。

String