2015-08-14 205 views
0

我想在Java的while循環中使用switch語句,但出現了問題。請看看在下面的代碼示例這也解釋了我的問題:在while循環中使用switch語句

Scanner input=new Scanner(System.in); 
    int selection = input.nextInt(); 

while (selection<4) 
     { switch(selection){ 
      case 1: 
       System.out.println("Please enter amount"); 
       double amount=input.nextDouble(); //object of scanner class 
       break; 

      case 2: 
       System.out.println("Enter ID number"); 
       break; 

      case 3: 
       System.out.println("Enter amount to be credited"); 
       break; 
          } 
System.out.println("1. Transfer\n2.Check balance\n3.Recharge"); 
    } 

如果我運行該代碼時,輸​​出如下:

1 
Please enter amount 
2000 
1. Transfer 
2.Check balance 
3.Recharge 
Please enter amount 
2 
1. Transfer 
2.Check balance 
3.Recharge 
Please enter amount 

當我輸入金額,然後,我會喜歡選擇另一個選項 - 輸出應該根據選擇的選項(你應該知道我想要這個代碼做什麼)。有人可以幫助糾正代碼嗎?

感謝

+1

您提示值,則不會再提示。你只需循環使用你在開始時提示的SAME值。 –

回答

1

你忘了再次要求選擇。輸入後不會改變。

Scanner input=new Scanner(System.in); 
int selection = input.nextInt(); 

while (selection<4) 
{ 
    switch(selection){ 
     case 1: 
      System.out.println("Please enter amount"); 
      double amount=input.nextDouble(); //object of scanner class 
      break; 

     case 2: 
      System.out.println("Enter ID number"); 
      break; 

     case 3: 
      System.out.println("Enter amount to be credited"); 
      break; 
     } 
     System.out.println("1. Transfer\n2.Check balance\n3.Recharge"); 
     selection = input.nextInt(); // add this 
} 

你甚至可以使用一個do ... while循環,而不是避免編寫input.nextInt();兩次

Scanner input=new Scanner(System.in); 
int selection; 

do 
{ 
    selection = input.nextInt(); 
    switch(selection){ 
     case 1: 
      System.out.println("Please enter amount"); 
      double amount=input.nextDouble(); //object of scanner class 
      break; 

     case 2: 
      System.out.println("Enter ID number"); 
      break; 

     case 3: 
      System.out.println("Enter amount to be credited"); 
      break; 
     } 
     System.out.println("1. Transfer\n2.Check balance\n3.Recharge"); 
} 
while(selection < 4); 
+0

傻我!感謝您找出答案 – Jspake

2

您目前獲取和設置選擇值一次和while循環之前,所以沒有辦法從循環中改變這一點。解決方案:從while循環的中的掃描器對象中獲取您的下一個選擇值。爲了理解這一點,從邏輯上思考問題並確保從心理上和紙面上瀏覽代碼,因爲問題不是一個真正的編程問題,而是一個基本的邏輯問題。


關於:

可能有人請幫助糾正代碼?

請不要要求我們這樣做,有幾個原因。

  1. 這不是一門功課完成服務
  2. 你向別人改變的代碼爲你,爲你學習如何編寫代碼編寫傷害自己。
  3. 真的這是一個基本的簡單問題,你有能力自己修復。請嘗試一下,只有在嘗試不成功的情況下,然後向我們展示您的嘗試。
+0

1.作業問題是創建一個完整的程序(比這更嚴密的方式,認真),我做了。 2.我不是故意要求任何人更改我的代碼。我只需要指導。這可能是我的語言。對不起,關於 3.感謝您的幫助:) – Jspake

-1

大於4的情況下,你的情況小於4.所以你不會退出循環,基本上break語句打破了開關並跳轉到循環,但比循環再次小於4,所以它又跳到開關等等。修復您的案例的大小,也許只是做一個

(selection != 1 || selection != 2 || selection !=3 || selection !=4)