【发布时间】:2020-04-02 04:29:15
【问题描述】:
我已经为此工作了几个小时,但我无法理解如何在这两个 do while 循环中实现 try-catch 以捕获用户输入非整数的情况。我知道有这方面的帖子,但我似乎无法得到它。我非常感谢任何建议。
public class Paint {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double wallHeight;
double wallWidth;
double wallArea = 0.0;
double gallonsPaintNeeded = 0.0;
final double squareFeetPerGallons = 350.0;
// Implement a do-while loop to ensure input is valid
// Handle exceptions(could use try-catch block)
do {
System.out.println("Enter wall height (feet): ");
wallHeight = scnr.nextDouble();
} while (!(wallHeight > 0));
// Implement a do-while loop to ensure input is valid
// Handle exceptions(could use try-catch block)
do {
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");
}
}
【问题讨论】:
标签: java try-catch inputmismatchexception