2016-09-30 80 views
1

當我點擊這個代碼重試,它的工作,並問多少次循環翻轉一枚硬幣,但只是打印「翻轉硬幣」,什麼都不做。誰知道怎麼修它?我認爲錯誤可能來自X已經小於numloop,但我不知道如何解決它。爲什麼此循環循環代碼但未執行正確的操作?

這裏是我的代碼:

import java.util.Scanner; 

public class coinFlip { 

    public static void main (String[]args)throws InterruptedException { 

    Scanner sc = new Scanner(System.in); 
    Scanner scan = new Scanner(System.in); 
    int numloop; 
    int x = 0; 
    String choice; 
    Boolean bool = true; 


    while (bool=true){ 
     System.out.println("How Many Coins Would You Like To Flip?"); 
     numloop = sc.nextInt(); 

     if (numloop == 13 || (numloop == 5 || (numloop == 8 || (numloop == 666)))) { 
     System.out.println("ILLUMINATI CONFIRMED ??????"); 
     System.out.println(); 
     } 

     System.out.println("Flipping Coin(s)..."); 
     System.out.println(); 

     while (x<numloop) { 

     int rng = (int)(Math.random()*10+1); 

     if (rng <= 5) { 

      System.out.println("You Flipped Heads"); 
     } 

     else { 
      System.out.println("You Flipped Tails"); 
     } 

     x=x+1; 
     } 


     System.out.println(); 
     System.out.println("Would You Like To 'Quit' Or 'Retry'?"); 
     choice = scan.nextLine(); 

     if (choice.equalsIgnoreCase("Quit")) { 
     System.out.println ("Have A Nice Day"); 
     Thread.sleep(1000); 
     System.exit(0); 
     } 

     if (choice.equalsIgnoreCase("Retry")) { 
     bool=true; 
     } 


    } 
    } 
} 

太感謝你了!

回答

4

你永遠不會在循環中重新初始化x,所以它仍然等於numLoop

x = 0添加到外部循環的頂部,每次用戶說要重試時它都會重置該值。

此外,雖然它沒有在這種情況下無所謂,這條線是錯誤的:

while (bool=true){ 

將分配給truebool,並將永遠繼續循環。您通常應該只說while (bool),但由於您從未將其設置爲false,因此您可以改爲while (true)

+0

非常感謝! – Smor

+2

@Smor這是使用你的調試器來逐步執行代碼的地方應該有所幫助。 –

+0

@PeterLawrey究竟是什麼?我正在使用Dr. Java btw – Smor

0

如果您將int x=0從初始while循環的外部移動到其內部,則不會出現此問題。每次用戶重試時它都會重置。

Scanner sc = new Scanner(System.in); 
    Scanner scan = new Scanner(System.in); 
    int numloop; 

    String choice; 
    Boolean bool = true; 


    while (bool=true){ 
     int x = 0; 
     System.out.println("How Many Coins Would You Like To Flip?"); 
     numloop = sc.nextInt(); 

     if (numloop == 13 || (numloop == 5 || (numloop == 8 || (numloop == 666)))) { 
      System.out.println("ILLUMINATI CONFIRMED ??????"); 
      System.out.println(); 
     } 

     System.out.println("Flipping Coin(s)..."); 
     System.out.println(); 

     while (x<numloop) { 

      int rng = (int)(Math.random()*10+1); 

      if (rng <= 5) { 

       System.out.println("You Flipped Heads"); 
      } 

      else { 
       System.out.println("You Flipped Tails"); 
      } 

      x=x+1; 
     } 


     System.out.println(); 
     System.out.println("Would You Like To 'Quit' Or 'Retry'?"); 
     choice = scan.nextLine(); 

     if (choice.equalsIgnoreCase("Quit")) { 
      System.out.println ("Have A Nice Day"); 
      Thread.sleep(1000); 
      System.exit(0); 
     } 

     if (choice.equalsIgnoreCase("Retry")) { 
      bool=true; 
     } 


    } 
}