2015-07-09 194 views
1

爲什麼Coins while循環只能在下面的代碼中循環一次?while循環只循環一次

該程序應該允許玩家獲得他們想要的硬幣數量,然後如果他們想要更多的硬幣可以返回。出於某種原因,儘管您一旦經過Coins循環並退出一次,無論您是否有任何硬幣,它都不再有效。

import java.util.Scanner; 
public class Coins 
{ 
    public static void main(String[]args) 
    { 
     int user; 
     int coins=1000; 
     int player=0; 
     boolean Coins=true; 
     boolean whatGame=true; 
     while(whatGame) 
     { 
      System.out.print("Press 1 to get more coins\n"); 
      Scanner myScan=new Scanner(System.in); 
      user=myScan.nextInt(); 
      if(user==1) 
      { 
       while(Coins) 
       { 
        if((coins>100)||(coins==100)) 
        { 
         System.out.print('\u000C'); 
         coins=coins-100; 
         player=player+100; 
         System.out.print("Only "+coins+" coins left.\n\n"); 
         System.out.print("You now have "+player+" coins.\n\n"); 
         System.out.println("Press 1 to get more coins\n\nPress 2 to play another game"); 
         user=myScan.nextInt(); 
         if(user==1) 
         { 
          System.out.print('\u000C'); 
          Coins=true; 
         } 
         else 
         { 
          System.out.print('\u000C'); 
          whatGame=true; 
          Coins=false; 
         } 
        } 
        else if((user==1)&&(coins<=0)) 
        { 
         System.out.print('\u000C'); 
         System.out.print("Sorry no coins left.\n"); 
         whatGame=true; 
         Coins=false; 
        } 
       } 
      } 
     } 
    } 
} 
+0

我看不出任何明顯的東西。每次使用'nextInt()'時都要設置一個斷點,並確保掃描器返回的值是您期望的值。 –

+2

你是否嘗試過使用調試器? – bhspencer

+0

爲什麼你使用這段代碼兩次:'user = myScan.nextInt();'? – MaxZoom

回答

1

好吧,我不明白你的遊戲...但你設置Coins=false內環路,那麼它將不會再運行。

如果你嘗試類似:

if(user==1) 
    { 
     Coins=true;   //new line here 
     while(Coins) { 

需要while循環開始每次。

您應該重新考慮重構您的解決方案。

+1

編輯:對不起錯誤的斷言 –

1
user=myScan.nextInt(); // from this moment on user may no longer be 1 
if(user==1) 
{ 
    System.out.print('\u000C'); 
    Coins=true; 
} 
else // thus this branch is executed 
{ 
    System.out.print('\u000C'); 
    whatGame=true; 
    Coins=false; // setting Coins to false, not re-entering loop 
}