2014-10-16 55 views
0

我對這個do while聲明感到困惑。我想讓如果用戶輸入y那麼它會循環回到do循環。我不知道如何命令回do循環,因爲C++如果我沒有弄錯,你可以使用goto關鍵字。如何在`do while`循環中回到頂部?

do 
    { 
    System.out.print("\nPlease Make A Choice :"); 
    input = stdin.readLine(); 
    x = Integer.parseInt(input); 

    if (x == 1)  
     CalculateCircleArea.GetRadius();  
    else if (x == 2) 
     CalculateRectangleArea.GetLengthAndHeight(); 
    else if (x == 3) 
     CalculateTriangleArea.GetHeightBaseAndBaseLength(); 
    else 

    System.out.print("\t  WRONG INPUT"); 
    String input2; 
    String abc = "\n\tDO YOU WANT TO CONTINUE?"; 
    String abc2 = "\n\t PLEASE CHOOSE (Y/N):"; 
    String abc3 = abc.concat(abc2); 
    System.out.print(abc3); 
    input2 = stdin.readLine(); 
    }while (choice == 'y'); 
+0

如果條件滿足時,它會再次重複,沒有必要爲一個'goto'聲明 – RockOnRockOut 2014-10-16 19:58:37

+0

看看我的回答(在C++一樣)這是你在找什麼對於。 – brso05 2014-10-16 19:59:40

+0

順便說一句,你永遠不會分配任何東西給你的'選擇'變量在循環體 – RockOnRockOut 2014-10-16 19:59:43

回答

2

應該使用這樣的:

while(choice.equalsIgnoreCase("y")) 

代替==這不是用來比較字符串。

另外我沒有看到選擇被設置,你可能想input2而不是選擇?

while(input2.equalsIgnoreCase("y") 
+0

@ brso05這是作品...非常感謝。你幫了我很多先生.. :)我會讓你的答案作爲我的參考..再次感謝 – Edie 2014-10-16 20:22:33

+0

歡迎你,我很高興我可以幫助! – brso05 2014-10-16 20:37:54

3

可以使用繼續語句啓動循環的新的迭代。

do{ 
    ... 
    continue; // Stops the current loop and continues to the next iteration. 
    ... 
}while(...); 

此外,我可以提供一些改進的代碼。

使用此相反的

input = stdin.nextLine(); 
x = Integer.parseInt(input); 

Scanner.nextInt()

x = stdin.nextInt(); 

將返回它找到,比讀一個字符串,並將其轉換爲int更有效的下一個整數。但是,使用當前配置通過使用try-catch塊檢查輸入錯誤時非常有用。

使用

System.out.print("\n\tDO YOU WANT TO CONTINUE? \n\t PLEASE CHOOSE (Y/N)"); 

而不是

String abc = "\n\tDO YOU WANT TO CONTINUE?"; 
String abc2 = "\n\t PLEASE CHOOSE (Y/N):"; 
String abc3 = abc.concat(abc2); 
System.out.print(abc3); 

前者很有道理,而且更有效率,因爲你不必在連接字符串等

而且,choice似乎沒有被宣佈或在任何地方使用。你確定你不應該使用input2?如果是這樣,則使用String.equalsIgnoreCase("")方法而不是==,因爲==比較對象引用而不是值。

1

我想你應該讀取用戶輸入正確的變量:

//... 
    input2 = stdin.readLine(); 
}while (choice == 'y'); 

通過

//... 
    choice = stdin.readLine(); 
}while ("y".equals(choice)); 
+0

除非'choice'看起來被聲明爲'char'。 – 2014-10-16 20:17:06

+0

是的,但它看起來像Edie喜歡打電話給readLine,女巫返回字符串 – 2014-10-16 20:21:11

0

更換不應該的條件是這樣嗎?

input2 = stdin.readLine(); 
} 
while (input2.equals("y")); 
+0

我不這麼認爲先生。但是謝謝,幫我一把。 :) – Edie 2014-10-16 20:16:16

0

使用choiceString只是爲了讓您的解決方案容易。

do{ 
    //.. 
    }while (choice == "y"); 

這個代碼將是正確的,如果choiceinterned否則其良好的使用equals()方法來比較字符串。

do{ 
    //... 
    input2 = stdin.readLine(); 
} 
while (input2.equals("y")); 

更多details

+0

@DavidConrad'input2'是一個'String'。 – gab06 2014-10-16 20:21:48

+1

是的這就是爲什麼我提到我用String作爲選擇。 – 2014-10-16 20:25:59

+0

哈哈@DavidConrad刪除了他的評論。 – gab06 2014-10-16 20:32:18