You may notice that entering a non-numeric value and clicking the ‘Check!’ button will cause a run-time error on the console. Therefore, your second task is to improve the application developed in Task 1 to ensure the user is only allowed to supply valid input values, i.e. a 4/5 number between 1 and 10 (inclusive). The application must still function as specified in Task 1 although you may remove the ‘Check!’ button if you wish.用Java编写
时间: 2024-03-16 20:41:10 浏览: 89
Get-dirs.rar_The Drive
好的,针对您的问题,我了解了您的需求,下面是使用 Java 编写的代码实现:
```java
import java.util.Scanner;
public class ValidInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int input = 0;
boolean validInput = false;
while (!validInput) {
System.out.print("Please enter a number between 1 and 10 (inclusive): ");
try {
input = Integer.parseInt(scanner.nextLine());
if (input >= 1 && input <= 10) {
validInput = true;
} else {
System.out.println("Invalid input. Please enter a number between 1 and 10 (inclusive).");
}
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please enter a number between 1 and 10 (inclusive).");
}
}
System.out.println("Valid input received: " + input);
}
}
```
这段代码使用了一个 while 循环,可以多次要求用户输入数字,直到用户输入了一个合法的数字。在每次循环中,程序会提示用户输入数字,并尝试将用户的输入解析为整数。如果用户输入的不是数字,则会抛出 NumberFormatException 异常,程序会提示用户重新输入。如果用户输入的数字不在 1 到 10 的范围内,则会提示用户重新输入。如果用户输入的数字是合法的,程序会将 validInput 标记设置为 true,退出循环并输出有效输入。
阅读全文