java - 在输入有效之前如何要求用户输入?
问题描述
我想让用户输入两个代表三角形边的双精度数,然后计算斜边。首先,用户指定他们想要的命令(A、B、C 或 Q),然后对于 A 和 B(侧面输入),要求他们输入双精度。现在,当他们没有输入双精度时,程序会要求他们输入第一个输入(A、B、C、Q)。我希望程序只要求他们再做一次,直到输入有效。
我的代码如下:
import java.util.InputMismatchException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Double sideA = null;
Double sideB = null;
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Enter command: ");
String command = scanner.nextLine();
try { // checks command, throws exception if not A, B, C or Q
if (command.equals("A")) {
System.out.println("Enter a value for side A:");
sideA = scanner.nextDouble(); // throws InputMismatchException if not a double
scanner.nextLine();
try {
if (sideA < 0 || sideA == 0.0) {
throw new InputMismatchException();
}
} catch (InputMismatchException e) {
System.out.println("Value is invalid. Must be positve and a double.");
}
}
else if (command.equals("B")) {
System.out.println("Enter a value for side B:");
sideB = scanner.nextDouble(); // throws InputMismatchException if not a double
scanner.nextLine();
try {
if (sideB < 0 || sideB == 0.0) {
throw new InputMismatchException();
}
} catch (InputMismatchException e) {
System.out.println("Value is invalid. Must be positive and a double.");
}
}
else if (command.equals("C")) {
Triangle calculate = new Triangle(sideA, sideB);
System.out.println(calculate.calcHypotenuse());
break;
}
else if (command.equals("Q")) {
System.exit(0);
}
else {
throw new IllegalArgumentException();
}
}
catch (IllegalArgumentException e) {
System.out.println("Command is invalid, Enter A, B, C, or Q.");
}
catch (InputMismatchException e) {
System.out.println("Value is invalid. Must be positve and a double.");
scanner.nextLine();
}
}
}
}
解决方案
快速查看您的代码,您只需将命令字符串移到 while 循环之外即可实现您想要的
String command = null;
while (true) {
if (command == null) {
System.out.println("Enter command: ");
command = scanner.nextLine();
}
....
}
还要考虑合并try-catch
代码,以免重复代码
推荐阅读
- mobile - 移动地理定位到地铁
- mysql - 当对 utf8mb4 数据和子字符串 ü 有索引时,MySql 和 MariaDB 中的错误?
- powershell-core - Powershell(pwsh)不接受命令行参数?
- c# - 如何在平台游戏中添加触摸按钮?
- themes - 远程与基于 Gem 的主题 - Github Pages / Jekyll 主题问题
- java - 春季MVC单元测试不抛出doThrow异常?
- sql - 获取总数和前 3 列
- python - 尽管在设置中指定了日期格式,但 Django 在运行测试时给了我一个“无效的日期格式”错误
- javascript - Rollup.js - 让 PostCSS 处理整个 bundle.css 而不是 rollup-plugin-svelte 中的单个文件
- android - 使用导航组件将自定义类型对象从片段传递到活动