用java,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.
时间: 2024-03-18 20:40:35 浏览: 273
java-mysql实验报告--网上书店.doc
以下是一个使用Java实现的改进版本,其中包含输入验证:
```java
import java.util.Scanner;
public class ImprovedApplication {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numerator = 0;
int denominator = 0;
// 输入验证
boolean validInput = false;
while (!validInput) {
System.out.print("Enter numerator (between 1 and 10): ");
numerator = scanner.nextInt();
System.out.print("Enter denominator (between 1 and 10): ");
denominator = scanner.nextInt();
if (numerator >= 1 && numerator <= 10 && denominator >= 1 && denominator <= 10) {
validInput = true;
} else {
System.out.println("Invalid input. Please enter numbers between 1 and 10.");
}
}
// 计算结果
int result = numerator * denominator;
System.out.println("Result: " + result);
}
}
```
在这个版本中,我们使用了一个 while 循环来验证输入。只有在用户输入的两个数字都在 1 到 10 的范围内时,才会退出循环并计算结果。如果用户输入了无效的数字,程序会提示用户重新输入,直到输入有效为止。这样可以确保程序不会出现运行时错误。
阅读全文