java - 当用户输入双精度以外的内容时,如何让 Java 引发异常?
问题描述
我正在编写一个程序,该程序根据墙壁的面积计算覆盖墙壁所需的油漆量。墙的高度和宽度(双打)由用户输入。如果给出无效输入(即字符串),我需要程序重新提示用户。如果用户输入无效数字(即负数),我已经有一个例外,但我找不到让程序显示我的错误消息并在输入字符串或字符时提示输入的方法。对此的任何帮助将不胜感激。
这是我的代码
导入 java.util.Scanner;
公共类油漆1 {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double wallHeight = 0.0;
double wallWidth = 0.0;
double wallArea = 0.0;
double gallonsPaintNeeded = 0.0;
final double squareFeetPerGallons = 350.0;
char userDone = 'n';
// Implement a do-while loop to ensure input is valid
while (userDone != 'q') {
try {
// Prompt user to input wall's height
System.out.println("Enter wall height (feet): ");
wallHeight = scnr.nextDouble();
if (wallHeight <= 0) { //error message for 0 or neg height input
throw new Exception ("Invalid height.");
}
// Prompt user to input wall's width
System.out.println("Enter wall width (feet): ");
wallWidth = scnr.nextDouble();
if (wallWidth <= 0) { //error message for 0 or neg width input
throw new Exception ("Invalid width.");
}
// Calculate and output wall area
wallArea = wallHeight * wallWidth;
System.out.println("Wall area: " + wallArea + " square feet");
// Calculate and output the amount of paint (in gallons) needed to paint the wall
gallonsPaintNeeded = wallArea/squareFeetPerGallons;
System.out.println("Paint needed: " + gallonsPaintNeeded + " gallons");
}
catch (Exception excpt) {
System.out.println(excpt.getMessage());
}
// Prompt user to quit or continue
System.out.println("Would you like to start a new calculation? \n(press any key to continue or 'q' to quit)");
userDone = scnr.next().charAt(0);
}
}
}
解决方案
双#parseDouble
使用它来解析输入并使用所需消息处理异常,以防解析失败。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
double n;
boolean valid;
do {
valid = true;
System.out.print("Enter a number: ");
try {
n = Double.parseDouble(kb.nextLine());
System.out.println("The number is " + n);
// ...your business logic
} catch (NumberFormatException | NullPointerException e) {
System.out.println("Invalid input. Try again");
valid = false;
}
} while (!valid);
}
}
示例运行:
Enter a number: a
Invalid input. Try again
Enter a number: xyz
Invalid input. Try again
Enter a number: 4.5
The number is 4.5
推荐阅读
- android - VoIP 通话后 Android 通知无法以正确的音量播放
- python-3.x - Python:在空闲多处理池中处理键盘中断
- scala - 如何在我的 scala play 应用程序中为 heroku 设置 log4j2 配置文件?
- javascript - 使用 Asp.Net Core,如何将视图作为新的浏览器选项卡打开,然后稍后再关闭
- python - 数学模块和变量函数
- javascript - 使用 Vue.js 存储和使用用户数据的最佳实践
- react-native - 反应原生动画未运行
- reactjs - 从 Firebase 存储播放音频文件可以在本地工作,但不能在已部署的应用程序上工作
- c++ - Google Mock 一个返回 void 但采用 std::unique_ptr 的方法
- reactjs - 有没有办法在 NextJS 路由中使用多个参数?