[英]How to make the program ask the user for input until they give a valid response?
你能幫我制作這個程序以獲得正確的號碼嗎? 程序應該檢查輸入類型,它應該是 int。 此外,程序應檢查該值是否在 1 到 10 之間。如果這些條件為真,則應將該值分配給 correctNumber。 到目前為止,我想出了這段代碼,但我很難讓它正常工作。
System.out.println("Enter a number from 1 to 10:");
Scanner scanner = new Scanner(System.in);
while (!scanner.hasNextInt() || !isCorrectNumber(scanner.nextInt())) {
System.out.println("Incorrect input!");
scanner.next();
}
int correctNumber = scanner.nextInt();
}
private static boolean isCorrectNumber(int n) {
return size >= 1 && size <= 10;
}
您在 while 條件下要求輸入 2 次 使用變量保存輸入,然后使用該變量
public static void main(String[] args) throws IOException {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String x = input.readLine();
while (!isInt(x)) {
x = input.readLine();
}
System.out.println(x);
}
我要求輸入,我得到一個字符串,現在我必須檢查這個字符串是否可以是一個數字。 為此,我創建了一個 boolean function isInt(String) 獲取字符串,如果它可以是數字則返回。
public static boolean isInt(String str) {//function that checks if String can be parsed into an integer
try {
Integer.parseInt(str);
return true;
}catch (NumberFormatException e) {
return false;
}
}
我希望我有所幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.