[英]how to check the data type validity of user's input (Java Scanner class)
我正在嘗試制作一個簡單的用戶界面,要求用戶輸入雙類型數字,如果他們的輸入不是雙類型,程序應該繼續打印提示,直到用戶輸入有效的雙類型。 我下面的代碼還不能正常工作,因為當用戶輸入有效的雙精度類型時,除非用戶輸入另一個雙類型數字,否則程序不會執行任何操作。 我猜 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?
由於您可能無法輸入雙精度值,因此最好讀入字符串,然后嘗試將其轉換為雙精度值。 標准模式是:
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");
}
}
在輸入雙userInput
值之前,循環無法退出,之后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);
當您將輸入掃描為字符串時,您可以解析它以查看它是否為雙精度值。 但是,如果將此靜態方法調用包裝在 try-catch 語句中,則可以處理未解析雙精度值的情況。
我認為您的代碼無法正常工作的原因是首先它會檢查給定的輸入是否為 double 類型( sc.hasNextDouble()
)如果不是,則再次輸入( sc.hasNext()
... 沒有使用這個行),然后您再次輸入( 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();
如果您第一次提供雙重輸入,則需要再次提供輸入,我認為如果任何時候您提供雙重輸入,那么您必須再次提供它,似乎不可能只提供一次輸入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.