[英]while true try catch nested
我是Java新手。 我希望代碼在用戶輸入錯誤類型的地方重復,而不是從頭開始。 在“輸入b:”或“輸入c:”時,它返回到開頭的“輸入a:”。 我只想重復一次,用戶輸入是a,b,c。 提前致謝。
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
boolean itsANumber = true;
while (itsANumber)
{
System.out.print("Enter a: ");
try
{
a = Double.parseDouble(sc.nextLine());
System.out.print("Enter b: ");
try
{
b = Double.parseDouble(sc.nextLine());
System.out.print("Enter c: ");
try
{
c = Double.parseDouble(sc.nextLine());
if (a == 0)
{
aZero();
} else
{
aNotZero();
}
} catch (NumberFormatException nfe)
{
System.out
.println("That's not a number, please try again!");
}
} catch (NumberFormatException nfe)
{
System.out
.println("That's not a number, please try again!");
}
} catch (NumberFormatException nfe)
{
System.out.println("That's not a number, please try again!");
}
}
}
介紹一種要求輸入數字的方法,然后調用它三次。 在方法內部,您將使用try-catch
進行while
循環。
public static void main(String... args) {
Scanner sc = new Scanner(System.in);
double
a = askForDouble(sc, "a"),
b = askForDouble(sc, "b"),
c = askForDouble(sc, "c");
}
static double askForDouble(Scanner sc, String varName) {
for (;/*ever*/;) {
System.out.format("Enter %s: ", varName);
System.out.flush();
try {
return Double.parseDouble(sc.nextLine());
} catch (NumberFormatExcetpion() {
System.out.println("That's not a number, please try again!");
}
}
}
您可以通過以下方法進行簡單的空檢查嘗試,這是原始代碼,可能需要更改
Double a = null;
Double b = null;
Double c = null;
Scanner sc = new Scanner(System.in);
while(true){
if(a != null){
System.out.println("Enter a :");
a = readFromInStream(sc, "a");
if(a == null) continue;
}
if(b != null){
System.out.println("Enter b :");
b = readFromInStream(sc, "b");
if(b == null) continue;
}
if(c != null){
System.out.println("Enter c :");
c = readFromInStream(sc, "c");
if(c == null) continue;
}
if(a != null && b != null && c != null){
break;
}
}
private Double readFromInStream(Scanner sc, String varStr){
Double temp = null;
try
{
temp = Double.parseDouble(sc.nextLine());
}catch(NumberFormatException e){
System.out.println("Invalid value for :"+varStr);
}
return temp;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.