這是一個小程式,它具有來自用戶的多個輸入以獲取輸入的最小數字。我試圖在同一個 try/catch 塊中捕獲 InputMismatchException ,但是如果用戶輸入除 int 以外的任何內容,例如要輸入的第二個或第三個 int ,那么它會跳回到用戶已經正確輸入的第一個輸入。有沒有更簡單的方法來解決這個問題,還是我需要為每個輸入創建單獨的 try/catch 塊?
public class GrabbingSmallestValueEntered {
public static void main(String[] args) {
//Scanner input = new Scanner(System.in);
boolean correctInput = true;
double a = 0;
double b = 0;
double c = 0;
Scanner input = new Scanner(System.in);
do {
try {
System.out.println("Input the first number: ");
a = input.nextDouble();
System.out.println("Input the second number: ");
b = input.nextDouble();
System.out.println("Input the third number: ");
c = input.nextDouble();
correctInput = false;
}catch (InputMismatchException ie) {
System.out.println("Only numbers allowed to be entered. No letters or words!");
input.nextLine();
}
} while (correctInput);
System.out.println("The smallest value is " smallest(a, b, c) "\n");
}
public static double smallest(double a, double b, double c)
{
return Math.min(Math.min(a, b), c);
}
uj5u.com熱心網友回復:
制作方法。你有一個任務:“要求一個雙重的,如果用戶沒有輸入一個,告訴他們,一直問直到他們輸入”。您希望以不同的提示重復運行此任務。
引數化差異并制定方法。然后呼叫:
public static double askDouble(Scanner input, String prompt) {
while (true) {
try {
System.out.println(prompt);
return input.nextDouble();
} catch (InputMismatchException e) {
System.out.println("Only numbers allowed, etc...");
input.next(); //don't mix nextLine and nextAnything else.
}
}
}
然后在你的 main 中呼叫那個方法(根本不需要 do/while 回圈,或者那個correctInput布林值。事實上,你的我的現在變成了 3 行非常簡單的行。是的方法!)
uj5u.com熱心網友回復:
您可以宣告一個雙精度陣列,讀取回圈中的值,在回圈中嘗試/捕獲例外。如果沒有錯誤,則增加索引。它可能是這樣的:
double[] a = [0,0,0];
int i = 0;
do {
try {
System.out.println("Input the first number: ");
a[i] = input.nextDouble();
i ;
} catch (InputMismatchException ie) {
System.out.println("Only numbers allowed to be entered. No letters or words!");
input.nextLine();
}
} while(i<3);
我沒有編譯器來測驗這個,如果有錯誤讓我知道我會盡力幫助你。
uj5u.com熱心網友回復:
有沒有更簡單的方法來解決這個問題,還是我需要為每個輸入創建單獨的 try/catch 塊?
是的。而不是讀出使用nextDouble(),只是做...
var input1Correct = false
while(!input1Correct) {
System.out.println("Input the first number: ");
a = input.nextLine();
input1Correct = validateInput(1)
}
然后您進行手動決議和驗證,如果一切正常,則繼續下一步。否則,要求重新輸入。
catch在這種情況下,您甚至不需要該子句。
這能解決您的問題嗎?在評論中告訴我。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/362402.html
