2014-10-28 38 views
0

我的循環從未停止,我似乎無法理解錯誤。我正在爲我的課程做一個項目 ,我對新的循環感到困惑。請告訴我如何 來解決這個問題。爲什麼我的「While」循環繼續進行?

import java.util.Scanner; 
public class FracCalc { 
    public static void main(String[] args) { 
     Scanner scan = new Scanner(System.in); { 
     boolean Quit = true; 

      System.out.println("Welcome to FracCalc"); 
      System.out.println("Type expressions with fractions, and I will evaluate them"); 
     String answer = scan.nextLine(); 
     while (Quit = true) { 

     if (answer.equals("Quit")){ 
      System.out.println("Thanks forr running FracCalc!"); 
      break; 

     } else { 
      System.out.println("I can only process 'Quit' for now"); 

     } 
     } 
    } 
    } 

} 
+1

你永遠設置爲「退出」,以虛假的變量。 – lzcd 2014-10-28 02:05:24

回答

1

String answer = scan.nextLine();放在循環中。

嘗試以下操作:

import java.util.Scanner; 
public class FracCalc { 
    public static void main(String[] args) { 
     Scanner scan = new Scanner(System.in); 

     System.out.println("Welcome to FracCalc"); 
     System.out.println("Type expressions with fractions, and I will evaluate them"); 

     String answer = scan.nextLine(); 

     do { 

      if (answer.equals("Quit")) { 
       System.out.println("Thanks forr running FracCalc!"); 
       break; 

      } else { 
       System.out.println("I can only process 'Quit' for now"); 
      } 

      answer = scan.nextLine(); 
     } while (true); 
    } 
} 
6

Quit = true將分配給trueQuit,並返回true。因此,你在做while (true),一個規範的無限循環。就像你正在測試Quit == true(注意雙等號),你絕不會把它分配給false,就像Izcd說的那樣。您可以用if輸入break,但answer只能在循環外分配一次。