[英]How to keep my code running after an exception is caught (Java)
我正在嘗試為一個可以處理來自用戶的所有異常和無效條目的類項目編寫代碼。
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;
final double squareFeetPerGallons = 350.0;
// Implement a do-while loop to ensure input is valid
// Prompt user to input wall's height
try {
//System.out.println("Enter wall height (feet): ");
do {//wallHeight = scnr.nextDouble();
System.out.println("Enter wall height (feet): ");
wallHeight = scnr.nextDouble();
if (wallHeight <= 0) {
System.out.println("Invalid height");
}
} while (wallHeight <= 0);
} catch (Exception excpt) {
System.out.println("Invalid height");
wallHeight = scnr.nextDouble();
}
// Implement a do-while loop to ensure input is valid
// Prompt user to input wall's width
do {
System.out.println("Enter wall width (feet): ");
wallWidth = scnr.nextDouble();
if (wallWidth <= 0) {
System.out.println("Invalid Width");
}
} 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");
}
}
我試圖通過分配的檢查是為 wallHeight 輸入一個字符串而不是雙精度值。 它打印“無效高度”,但隨后程序停止運行並返回錯誤。 如何讓它繼續運行並再次提示用戶輸入有效信息?
if (in.hasNextDouble()) {
double a = in.hasNextDouble() ;
System.out.println(a);
} else {
System.out.println("Invalid input");
}
這甚至可以防止 InputMismatchException 被拋出,因為在閱讀它之前你總是確保它匹配。
您當前提示輸入的方法(在wallWidth
和wallHeight
)存在缺陷,因為您捕獲了一個幾乎可以肯定是InputMismatchException
的異常(然后您未能使用不是數字的標記)。 我強烈建議您將提示提取到另一種方法; 就像是
private static double readWallDimension(Scanner scnr, String dimension) {
for (;;) {
try {
System.out.printf("Enter wall %s (feet):%n", dimension);
double dim = scnr.nextDouble();
if (dim <= 0) {
System.out.printf("Invalid %s%n", dimension);
} else {
return dim;
}
} catch (InputMismatchException excpt) {
System.out.printf("Invalid %s%n", dimension);
scnr.nextLine();
}
}
}
然后您的main
方法要簡單得多,調用該方法兩次(並且兩次都在本地處理異常)。
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
final double squareFeetPerGallons = 350.0;
double wallHeight = readWallDimension(scnr, "height");
double wallWidth = readWallDimension(scnr, "width");
// Calculate and output wall area
double 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
double gallonsPaintNeeded = wallArea / squareFeetPerGallons;
System.out.println("Paint needed: " + gallonsPaintNeeded + " gallons");
}
這是基於您的代碼的工作變體,帶有修復和解釋:
// Implement a do-while loop to ensure input is valid
// Prompt user to input wall's height
do { // moved one level up <- enable repeated input until it is valid
try { // moved one level down <- catch exception where it occurs
System.out.println("Enter wall height (feet): ");
wallHeight = scnr.nextDouble();
if (wallHeight <= 0) {
System.out.println("Invalid height");
}
} catch (Exception excpt) { // generally better: InputMismatchException
System.out.println("Invalid height");
scnr.nextLine(); // SKIP THIS INVALID LINE.
// Otherwise calling nextDouble() only throws the same exception as previously.
}
} while (wallHeight <= 0);
請注意,這應該符合 OP。 除此以外:
do - while
提取到用於讀取任何數字輸入的專用方法應該是可行的方法。scnr.hasNextDouble()
+ scnr.nextLine()
的組合。 您可以閱讀這些方法的javadoc以完全了解它們的作用。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;
boolean validNumber = false;
final double squareFeetPerGallons = 350.0;
// Implement a do-while loop to ensure input is valid
// Prompt user to input wall's height
do {
System.out.println("Enter wall height (feet): ");
if (scnr.hasNextDouble()) {
wallHeight = scnr.nextDouble();
validNumber = true;
if (wallHeight >0) {
wallHeight = wallHeight;
} else {
System.out.println("Must be greater than 0. Try again.");
validNumber = false;
}
} else {
System.out.println("Invalid input. Try again.");
System.out.println();
validNumber = false;
scnr.next();
}
} while (!validNumber);
// Implement a do-while loop to ensure input is valid
// Implement if-else loops to ensure correct value/type is given
// Prompt user to input wall's width
validNumber = false;
do {
System.out.println("Enter wall width (feet): ");
if (scnr.hasNextDouble()) {
wallWidth = scnr.nextDouble();
validNumber = true;
if (wallWidth >0) {
wallWidth = wallWidth;
} else {
System.out.println("Must be greater than 0. Try again.");
validNumber = false;
}
} else {
System.out.println("Invalid input. Try again.");
System.out.println();
validNumber = false;
scnr.next();
}
} while (!validNumber);
// 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");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.