【问题标题】:how to stop the while loop in java? [duplicate]如何停止java中的while循环? [复制]
【发布时间】:2017-07-23 10:05:02
【问题描述】:

我是 Java 新手,我正在创建一个简单的计算器。我使用while循环连续运行但无法停止,请帮我写代码。

我的计算器类代码是:

package calculator;

import java.util.Scanner;

public class Calculator {

    public static void main(String[] args) {
        Boolean keepRunning = true;
        while (keepRunning) {
            double a, b, out;
            int n;
            String ans = null;
            Scanner in = new Scanner(System.in);
            System.out.println("Enter two Numbers ");
            a = in.nextDouble();
            b = in.nextDouble();

            System.out.println("Enter the mode of operation:" + "\n"
                    + "1. Addition" + "\n"
                    + "2. Subtraction" + "\n"
                    + "3. Multiplication" + "\n"
                    + "4. Division");
            n = in.nextInt();
            switch(n){
                case 1:
                    out = add(a,b);
                    System.out.println("The output is: "+ out );
                    break;
                case 2:
                    out = sub(a,b);
                    System.out.println("The output is: "+ out );
                    break;
                case 3:
                    out = mul(a,b);
                    System.out.println("The output is: "+ out );
                    break;
                case 4:
                    out = div(a,b);
                    System.out.println("The output is: "+ out );
                    break;
                default:
                    System.out.println("Enter Valid option");
                    break;                
            }
            System.out.println("Do you want to continue? (Y/N)");
            Scanner in1 = new Scanner(System.in);
            ans = in1.next();

            if(ans == "Y" || ans == "y"){

            }else if(ans == "N" || ans == "n"){
                keepRunning = false;    
                System.exit(0);
            }        
        }      
    }

    public static double add(double a, double b){
        return a+b;
    }
    public static double sub(double a, double b){
        return a-b;
    }
    public static double mul(double a, double b){
        return a*b;
    }
    public static double div(double a, double b){
        return a/b;
    }
}

if 循环根本没有运行它有什么问题。

注意:这个问题在 Stackoverflow 中已经存在,但我找不到答案。

【问题讨论】:

    标签: java loops if-statement while-loop calculator


    【解决方案1】:

    不要将字符串与 Java 中的 == 进行比较,例如使用 "N".equals(ans)。注意@EJP 为您发布的副本

    【讨论】:

      猜你喜欢
      • 2010-09-26
      • 2013-09-11
      • 2023-01-10
      • 1970-01-01
      • 2022-08-16
      • 2015-10-04
      • 1970-01-01
      • 2015-03-25
      • 1970-01-01
      相关资源
      最近更新 更多