【问题标题】:Why deos my "While" loop keep going on?为什么我的“While”循环一直在进行?
【发布时间】:2014-10-28 02:03:12
【问题描述】:

我的循环永远不会停止,我似乎无法理解出了什么问题。我正在做 我的班级的一个项目,我对循环很陌生,所以有点困惑。请告诉我如何 来解决这个问题。

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");

        }
        }
    }
  }

}

【问题讨论】:

  • 您永远不会将名为“Quit”的变量设置为 false。

标签: java loops if-statement while-loop


【解决方案1】:

Quit = true 会将true 分配给Quit,并返回true。因此,您正在执行while (true),这是一个规范的无限循环。即使您正在测试Quit == true(注意双重等号),您也永远不会将它分配给false,正如Izcd 所说。您可以将break 与您的if 分开,但answer 在循环外只分配一次。

【讨论】:

    【解决方案2】:

    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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-05
      • 2012-11-07
      • 2021-08-20
      相关资源
      最近更新 更多