当前位置: 首页 > 知识库问答 >
问题:

创建计算器但无法退出

皇甫繁
2023-03-14

我需要编码方面的帮助。我再次练习我的java编程,今天我创建了一个计算器,它具有与真正的计算器相同的功能,但我再次遇到错误,无法再次计算。

好的,我希望我的计算器工作的方式是,而不是像这样从用户那里获取逐行输入:-

代码内输出

Enter Number: 1
Enter Operator (+,-, /, *, ^ (Power)  or  s (Square): +
Enter Number: 2
Ans: 3

我想让它在用户按下enter键时进行计算,如下所示:-

我想要的输出

enter number: 1+2*4 
Ans: 12

因此,他们可以在按下enter calculate键之前添加任意长的数字。用户应该能够在计算循环中使用计算器时将数字重置为。

在代码的开头,它会要求用户输入继续或退出计算器。然后如果继续,它将运行计算。计算器将循环运行,直到用户按E退出计算器,如果退出,它将退出代码。

这就是我犯错误的地方。首先,我不知道如何在循环计算器中打破循环,第二,在代码开始时,当用户按E时,它本应退出计算器,但它没有退出。第三个错误是,当用户使用正方形进行计算时,我希望它直接显示答案,而不是询问另一个数字。

我想简化计算部分的publicstaticvoidmain(String[]args)中的代码。是否可以将开关盒放入方法中,并在main中调用它?或者你对如何简化计算部分有什么建议?

请帮助我:(

public class TestingCalculator {

     public static void main(String[] args){

          double answer = 0;
          double numA, numB;
          char operator;

          char activateCalc; 
          boolean calculator = false;

          System.out.println("Welcome to the Calculator.");
          System.out.print(" Continue (Press Y) \n Exit (Press E) \n: ");

          Scanner ans = new Scanner(System.in);
          String a = ans.next();
          activateCalc = a.charAt(0);

          while (activateCalc != 'E' || activateCalc != 'e') {

               Scanner input = new Scanner(System.in);

               System.out.print("Enter number: "); 

               String n =input.next();
               numA = Double.parseDouble(n); 

               while (calculator = true) {

                     //User enter their operator.
                    System.out.print("Enter Operator (+,-, /, *, ^ (Power)  or  s (Square): ");
                    operator = input.next().charAt(0);

                    System.out.print("Enter number: ");  //User enter the continues number
                    numB = input.nextDouble();


                     switch (operator) {

                          case '=':
                               System.out.print(answer);   
                               break;
                          case '+':
                               answer = add(numA,numB);  
                               break;
                         case '-':
                               answer =subtract(numA,numB);
                              break;
                         case '*':
                               answer = multiply(numA,numB);
                               break;
                         case '/':
                               answer = divide(numA,numB);
                               break;
                         case '^':
                              answer = power(numA, numB);
                               break;
                         case 's':
                         case 'S':
                               answer = Math.pow(numA, 2);
                              break;
               }

               //The calculation answer of the user input
               System.out.println("Answer: " + answer);
               numA = answer;

               // to exit calculator.
               System.out.println("Press E to Exit the calculator: ");

                    if (activateCalc = 'E' || activateCalc = 'e') {
                         break;
                    }

               }  
          }

          ans.close();
     }

     //Method for the operators.
    static double add(double numA, double numB) {

          double answer =  numA + numB;
          return answer;
     }

    static double subtract(double numA, double numB) {

          double answer = numA - numB;
          return answer;        
     }

     static double multiply(double numA, double numB) {

          double answer = numA * numB;
          return answer;   
     }

     static double divide(double numA, double numB) {

          double answer = numA / numB;
          return answer;
     }    
     static double power(double numA, double numB) {

          int answer = (int) Math.pow(numA, numB);
          return answer;
     }    
     static double Square(double numA, double numB) {

          int answer = (int) Math.pow(numA, 2);
          return answer;
     }    
}

共有3个答案

燕琨
2023-03-14

这个问题需要调试细节,所以我们开始:

  1. 由于以下错误,您的代码似乎无法编译:
if (activateCalc = 'E' || activateCalc = 'e') {
    break;
}

您必须使用比较运算符而不是赋值运算符。

类似的问题在你的内部循环而(计算器=true)-有一个警告,这个值从未被使用-但这并没有太大的影响。

您无法退出循环,因为您从未检查输入是否退出,它应该是:

System.out.println("Press E to Exit the calculator: ");
activateCalc = input.next().charAt(0);
赵元白
2023-03-14

尝试下面的代码和一个建议尝试处理负面的情况。

public static void main(String[] args) {

    double answer = 0;
    double numA, numB;
    char operator;

    char activateCalc;
    boolean calculator = false;

    System.out.println("Welcome to the Calculator.");
    System.out.print(" Continue (Press Y) \n Exit (Press E) \n: ");

    Scanner ans = new Scanner(System.in);
    Scanner input = new Scanner(System.in);
    activateCalc = input.next().charAt(0);
    while (true) {
        if (activateCalc != 'E' && activateCalc != 'e') {
            System.out.print("Enter number: ");

            String n = input.next();
            numA = Double.parseDouble(n);

            // User enter their operator.
            System.out.print("Enter Operator (+,-, /, *, ^ (Power)  or  s (Square): ");
            operator = input.next().charAt(0);

            System.out.print("Enter number: "); // User enter the continues number
            numB = input.nextDouble();

            switch (operator) {

            case '=':
                System.out.print(answer);
                break;
            case '+':
                answer = add(numA, numB);
                break;
            case '-':
                answer = subtract(numA, numB);
                break;
            case '*':
                answer = multiply(numA, numB);
                break;
            case '/':
                answer = divide(numA, numB);
                break;
            case '^':
                answer = power(numA, numB);
                break;
            case 'S':
            case 's':
                answer = Math.pow(numA, 2);
                break;
            default:
                answer = 0;
            }

            // The calculation answer of the user input
            System.out.println("Answer: " + answer);
            numA = answer;

            // to exit calculator.
            System.out.println("Press E to Exit the calculator or Y to continue : ");
            activateCalc = input.next().charAt(0);
            if(activateCalc != 'E' && activateCalc != 'e')continue;
        }
        System.out.println("Thank you for using the calculator. By :) ");
        ans.close();
        break;
    }

}

// Method for the operators.
static double add(double numA, double numB) {

    double answer = numA + numB;
    return answer;
}

static double subtract(double numA, double numB) {

    double answer = numA - numB;
    return answer;
}

static double multiply(double numA, double numB) {

    double answer = numA * numB;
    return answer;
}

static double divide(double numA, double numB) {

    double answer = numA / numB;
    return answer;
}

static double power(double numA, double numB) {

    int answer = (int) Math.pow(numA, numB);
    return answer;
}

static double Square(double numA, double numB) {

    int answer = (int) Math.pow(numA, 2);
    return answer;
}
葛阳华
2023-03-14

我没有试图识别应用程序的问题,而是决定专注于生成一个按您想要的方式工作的程序(使用您指定的输入)。代码有点大,但我试图让它保持良好的注释,以便您理解我所做的。我知道有些事情可能仍然有点混乱,所以我会模拟运行程序,试图让它更清楚它是如何工作的。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class TestingCalculator 
{
    //-------------------------------------------------------------------------
    //      Methods
    //-------------------------------------------------------------------------
    /**
     * Evaluates a mathematical expression.
     * 
     * @param       line Mathematical expression. This line cannot have blank
     * spaces
     * @return      Result of this mathematical expression
     */
    public static String calc(String line)
    {
        while (!hasOnlyNumbers(line)) {
            // Checks if line has parentheses
            if (line.contains("(")) {
                // Get index of the most nested parentheses
                int parentheses_begin = line.lastIndexOf("(");
                int parentheses_end = line.substring(parentheses_begin).indexOf(")");
                String ans = calc(line.substring(parentheses_begin+1, parentheses_end));

                // Replaces content of parentheses with the result obtained
                if (line.length()-1 >= parentheses_end+1)
                    line = line.substring(0,parentheses_begin)+ans+line.substring(parentheses_end+1);
                else
                    line = line.substring(0,parentheses_begin)+ans;
            }
            // Checks if line has potentiation operator
            else if (line.contains("^")) {
                int opIndex = line.indexOf("^");
                String n1 = extractFirstNumber(line, opIndex);
                String n2 = extractSecondNumber(line, opIndex);
                double ans = power(Double.valueOf(n1), Double.valueOf(n2));

                line = calc(parseLine(line, n1, n2, opIndex, ans));
            }
            // Checks if line has square operator
            else if (line.contains("s")) {
                int opIndex = line.indexOf("s");
                String n1 = extractFirstNumber(line, opIndex);
                double ans = square(Double.valueOf(n1));

                line = calc(parseLine(line, n1, opIndex, ans));
            }
            // Checks if line has multiplication operator
            else if (line.contains("*")) {
                int opIndex = line.indexOf("*");
                String n1 = extractFirstNumber(line, opIndex);
                String n2 = extractSecondNumber(line, opIndex);
                double ans = multiply(Double.valueOf(n1), Double.valueOf(n2));

                line = calc(parseLine(line, n1, n2, opIndex, ans));
            }
            // Checks if line has division operator
            else if (line.contains("/")) {
                int opIndex = line.indexOf("/");
                String n1 = extractFirstNumber(line, opIndex);
                String n2 = extractSecondNumber(line, opIndex);
                double ans = divide(Double.valueOf(n1), Double.valueOf(n2));

                line = calc(parseLine(line, n1, n2, opIndex, ans));
            }
            // Checks if line has sum operator
            else if (line.contains("+")) {
                int opIndex = line.indexOf("+");
                String n1 = extractFirstNumber(line, opIndex);
                String n2 = extractSecondNumber(line, opIndex);
                double ans = add(Double.valueOf(n1), Double.valueOf(n2));

                line = calc(parseLine(line, n1, n2, opIndex, ans));
            }
            // Checks if line has subtraction operator
            else if (line.contains("-")) {
                int opIndex = line.indexOf("-");
                String n1 = extractFirstNumber(line, opIndex);
                String n2 = extractSecondNumber(line, opIndex);
                double ans = subtract(Double.valueOf(n1), Double.valueOf(n2));

                line = calc(parseLine(line, n1, n2, opIndex, ans));
            }
        }

        // Returns line only when it has only numbers
        return line;
    }

    /**
     * Checks if a line contains only numbers.
     * 
     * @param       line Line to be analyzed
     * @return      If a line contains only numbers
     */
    private static boolean hasOnlyNumbers(String line)
    {
        return line.matches("^[0-9.]+$");
    }

    /**
     * Given a mathematical expression, replaces a subexpression for a value.
     * 
     * @param       line Mathematical expression
     * @param       n1 Number to the left of the subexpression operator
     * @param       n2 Number to the right of the subexpression operator
     * @param       opIndex Operator index of the subexpression
     * @param       ans Value that will replace the subexpression
     * @return      New mathematical expression with the subexpression replaced
     * by the value
     */
    private static String parseLine(String line, String n1, String n2, int opIndex, double ans)
    {
        int lenFirstNumber = n1.length();
        int lenSecondNumber = n2.length();

        if (line.length()-1 >= opIndex+lenSecondNumber+1)
            return line.substring(0, opIndex-lenFirstNumber)+ans+line.substring(opIndex+lenSecondNumber+1);

        return line.substring(0, opIndex-lenFirstNumber)+ans;
    }

    /**
     * Given a mathematical expression, replaces a subexpression for a value.
     * 
     * @param       line Mathematical expression
     * @param       n1 Number to the left of the subexpression operator
     * @param       opIndex Operator index of the subexpression
     * @param       ans Value that will replace the subexpression
     * @return      New mathematical expression with the subexpression replaced
     * by the value
     */
    private static String parseLine(String line, String n1, int opIndex, double ans)
    {
        int lenFirstNumber = n1.length();

        if (line.length()-1 >= opIndex+2)
            return line.substring(0, opIndex-lenFirstNumber)+ans+line.substring(opIndex+2);

        return line.substring(0, opIndex-lenFirstNumber)+ans;
    }

    /**
     * Extracts the first number from an operation. <br />
     * <h1>Example:<h1> <br />
     *  <b>Line:</b>        1+2*3   <br />
     *  <b>opIndex:</b>     3       <br />
     *  <b>Return:</b>      2       <br />
     * 
     * @param       line Mathematical expression
     * @param       opIndex Index of the operator to which the number to be 
     * extracted belongs to
     * @return      Number to the left of the operator
     */
    private static String extractFirstNumber(String line, int opIndex)
    {
        StringBuilder num = new StringBuilder();
        int i = opIndex-1;

        while (i>=0 && (Character.isDigit(line.charAt(i)) || line.charAt(i) == '.')) {
            num.append(line.charAt(i));
            i--;
        }

        // Reverses the result, since the number is taken from the end to the 
        // beginning
        num = num.reverse();

        return num.toString();
    }

    /**
     * Extracts the second number from a math operation. <br />
     * <h1>Example:<h1> <br />
     *  <b>Line:</b>        1+2*3   <br />
     *  <b>opIndex:</b>     3       <br />
     *  <b>Return:</b>      3       <br />
     * 
     * @param       line Mathematical expression
     * @param       opIndex Index of the operator to which the number to be 
     * extracted belongs to
     * @return      Number to the right of the operator
     */
    private static String extractSecondNumber(String line, int opIndex)
    {
        StringBuilder num = new StringBuilder();
        int i = opIndex+1;

        while (i<line.length() && (Character.isDigit(line.charAt(i)) || line.charAt(i) == '.')) {
            num.append(line.charAt(i));
            i++;
        }

        return num.toString();
    }

    // Method for the operators.
    private static double add(double numA, double numB) 
    {
        double answer = numA + numB;
        return answer;
    }

    private static double subtract(double numA, double numB) 
    {
        double answer = numA - numB;
        return answer;
    }

    private static double multiply(double numA, double numB) 
    {
        double answer = numA * numB;
        return answer;
    }

    private static double divide(double numA, double numB) 
    {
        double answer = numA / numB;
        return answer;
    }

    private static double power(double numA, double numB) 
    {
        int answer = (int) Math.pow(numA, numB);
        return answer;
    }

    private static double square(double num) 
    {
        int answer = (int) Math.pow(num, 2);
        return answer;
    }

    //-------------------------------------------------------------------------
    //      Main
    //-------------------------------------------------------------------------
    public static void main(String[] args) throws IOException 
    {
        char option;
        String inputLine = "";
        BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

        System.out.println("Welcome to the Calculator.");
        System.out.print(" Continue (Press Y) \n Exit (Press E) \n: ");

        option = input.readLine().charAt(0);

        while (option != 'E' && option != 'e') {
            // Gets user input
            System.out.print("Enter mathematical expression: ");

            inputLine += input.readLine();

            // Processes input
            inputLine = inputLine.replaceAll(" ", "");
            inputLine = inputLine.replaceAll("S", "s");

            // Evaluates input
            System.out.println("Evaluating...");
            String ans = TestingCalculator.calc(inputLine);

            // Displays answer
            System.out.println("Ans: "+ans);

            // Checks if the user wants to continue running the program
            System.out.print("Press E to Exit the calculator: ");

            inputLine = input.readLine();

            if (inputLine.length() > 0)
                option = inputLine.charAt(0);
        }

        input.close();
    }
}
Enter mathematical expression: (1+2*4)/3
Evaluating...
Ans: 3.0
Enter mathematical expression: 1+2*9/3
Evaluating...
Ans: 7.0

输入:(1 2*4)/3


    calc( (1+2*4)/3 )
        not hasOnlyNumbers( (1+2*4)/3) ) ? true
        ( (1+2*4)/3) ) contains '(' ? true
            int parentheses_begin = 0
            int parentheses_end = 6
            String ans = calc( 1+2*4 )
                calc( 1+2*4 )
                    not hasOnlyNumbers( 1+2*4 ) ? true
                    ( 1+2*4 ) contains '(' ? false
                    ( 1+2*4 ) contains '^' ? false
                    ( 1+2*4 ) contains 's' ? false
                    ( 1+2*4 ) contains '*' ? true
                        int opIndex = 3
                        int n1 = 2
                        int n2 = 4
                        String ans = n1 * n2 = 2 * 4 = 8

                        line = calc( 1+8 )
                            calc( 1+8 )
                                not hasOnlyNumbers( 1+8 ) ? true
                                ( 1+8 ) contains '(' ? false
                                ( 1+8 ) contains '^' ? false
                                ( 1+8 ) contains 's' ? false
                                ( 1+8 ) contains '*' ? false
                                ( 1+8 ) contains '/' ? false
                                ( 1+8 ) contains '+' ? true
                                    int opIndex = 1
                                    int n1 = 1
                                    int n2 = 8
                                    String ans = n1 + n2 = 1 + 8 = 9
                                    line = calc( 9 )
                                        calc( 9 )
                                            not hasOnlyNumbers( 9 ) ? false
                                            return 9
                                    line = 9
                                not hasOnlyNumbers( 9 ) ? false
                                return 9
                        line = 9
                    not hasOnlyNumbers( 9 ) ? false
                    return 9
            ans = 9
            (9-1 >= 6+1) ? true
                line = 9/3
        not hasOnlyNumbers( 9/3 ) ? true
        ( 9/3 ) contains '(' ? false
        ( 9/3 ) contains '^' ? false
        ( 9/3 ) contains 's' ? false
        ( 9/3 ) contains '*' ? false
        ( 9/3 ) contains '/' ? true
            int opIndex = 1
            String n1 = 9
            String n2 = 3
            double ans = 9 / 3 = 3

            line = calc( 3 )
                calc( 3 )
                    not hasOnlyNumbers( 3 ) ? false
                    return 3
            line = 3
        not hasOnlyNumbers( 3 ) ? false
        return 3

  • 不检查用户提供的输入是否有效
  • 为了保持运算符之间的优先级(必须先进行求幂/求根,然后进行乘法/除法,最后进行加法/减法运算),必须保持计算方法中验证的运算顺序。
  • 我在Scanner类中遇到问题,因此我使用BufferedReader读取输入
  • 平方运算必须按如下方式进行:

希望这能有所帮助。如果你不明白什么,告诉我我可以给你解释。

 类似资料:
  • 错误信息 当我第一次运行Docker Quickstart Terminal时,我收到以下消息,机器无法创建。 创建机器出错:机器创建过程中驱动程序出错:退出状态1看起来出了问题…按任意键继续… 有人知道吗? 相关组件的版本: 泊坞工具盒-1.9.0 视窗 7 sp1 虚拟盒版本 5.0.8 r103449

  • 每次我尝试创建一个新的计算机时,它都会说创建失败了,所以我无法工作。我的区域是francecentral,我尝试了不同大小的虚拟机

  • 我正在使用Laravel出纳实现一个定期付款系统。我需要一个订阅计划。Stripe doc说:“您可以使用API或Stripe仪表板创建计划。”但当我点击仪表板上的链接进入仪表板时,我看不到任何创建任何计划的方法。 问:那么,我如何在那里创建一个计划,以便能够以以下方式在服务器端Laravel实现中使用它? 我需要将该计划用作变量的值。

  • 如何创建计算字段以及怎么样从应用程序中使用别名。 计算字段 存储在数据库表中的数据一般不是应用程序所需要的格式,例如: 显示两个信息,但不是在用一个表 不同列中,但程序需要把他们作为一个格式的字段检索出来 列数据是大小混合,但程序需要把所以数据按大写表示。 物品订单表存储的物品的价格和数量,但没有存储物品的总价,打印时,需要物品的总价格。 根据需要表的数据进行总数,平均数等计算。 上面的情况都我们

  • 我得到以下错误,我不知道为什么。我在多个环境中设置了我的项目,从来没有任何问题,但最近我将项目添加到运行Windows8的环境中,所有的东西都设置正确(例如Maven...),我似乎得到了这个问题 删除.m2存储库,Maven->Update Project... 删除所有文件,Maven->Update project... 更新项目时尝试选择“强制更新快照/发布” 有人对我可以尝试的东西有其他

  • Itinerary类存储有关具有以下成员的旅程的信息: •一个名为flights的私有ArrayList数据字段,其中包含按DepartureTime递增顺序排列的旅程航班。(提示:您不需要进行排序。) •使用ArrayList类型的指定航班创建旅程的构造函数。 •名为getTotalFlightTime()的方法,以分钟为单位返回旅程的总飞行时间。(提示:为每个飞行对象调用getFlightTi