【发布时间】:2020-04-11 13:42:54
【问题描述】:
下面是我的代码,我想在 do/while 循环中添加一个 try/catch 块,以便为除数字以外的用户输入引发异常(即,如果用户输入 20 而不是 20)。我不确定如何编写比较来引发异常。
import java.util.Scanner;
public class Paint1 {
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;
double squareFeetPerGallons = 350.0;
// Prompt user to input wall's height
System.out.println("Enter wall height (feet): ");
wallHeight = scnr.nextDouble();
while (wallHeight <= 0) {
do {
System.out.println("Wall height must be a number greater then zero and in arabic numeral format.");
System.out.println("Enter wall height (feet): ");
wallHeight = scnr.nextDouble();
} while (wallHeight <= 0);
}
// Prompt user to input wall's width
System.out.println("Enter wall width (feet): ");
wallWidth = scnr.nextDouble();
while (wallWidth <= 0) {
do {
System.out.println("Wall width must be a number greater then zero and in arabic numeral format.");
System.out.println("Enter wall width (feet): ");
wallWidth = scnr.nextDouble();
} while (wallWidth <= 0);
}
// 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");
}
}
【问题讨论】:
-
这不是 JavaScript 代码,而是 Java。两种完全不同的语言。
标签: java