2014-10-28 92 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只能在循环外分配一次。