如何使用Java计算器进行单操作数计算?

时间:2014-10-22 04:47:16

标签: java math if-statement operators calculator

我一直在尝试用Java创建一个简单的计算器,我已经成功地使程序能够使用双操作数方程(+, - ,*,/和^)。但是,我想知道我怎么能够做单操作数数学问题 - 绝对值(使用符号" |"),平方根(使用符号' v') ,舍入到最接近的整数(使用符号'〜'),sin(s),cos(c)和tangent(t)。

我尝试了绝对值操作数,可以在:

中看到
if (operator == '|') {
            answer = Math.abs(numA);
}
// In the main class

double absolute(double a) {
            double answer = Math.abs(a);
            return answer;
}
// In the maths class

此代码仅在您输入值时才有效,例如:-3 | -3(注意:我注意到它只是执行绝对值操作的第一个数字。第二个数字可以是任何数字你想要的(如果你输入-3 | -4,你的答案仍然是3),只要它确实是一个数字。

任何帮助解决这个问题并帮助搞清楚其他单操作数操作的人都将不胜感激!

提前致谢!

我的程序的源代码如下:

package calculator;
import java.util.Scanner;

public class Calculator {

public static void main(String[] args) {

    System.out.println("Hello, welcome to my calculator");
    System.out.println("Enter in some stuff you want to me to calculate");

    Scanner scan = new Scanner(System.in);
    System.out.println("If you need help please type \"help\"");
    System.out.println("If at anytime you want to leave, type \"quit\"");
    System.out.println("Hit enter to continue.");

    String s1 = scan.nextLine();

    if (s1.equals("help")){
        System.out.println(" ");

        System.out.println("Double operand commands:");
        System.out.println("Addition: '+' (Ex: 'a + b' )");
        System.out.println("Subtraction: '-' (Ex: 'a - b' )");
        System.out.println("Multiplication: '*' (Ex: 'a * b' ) ");
        System.out.println("Division: '/' (Ex: 'a / b' )");
        System.out.println("Exponents: '^' (Ex: 'a ^ b' )");

        System.out.println(" ");
    }

    Scanner input = new Scanner(System.in);

    Maths maths = new Maths();

    double answer = 0;
    double numA, numB;
    char operator;
    boolean quit = false;


    while (true) {

    System.out.print("Please enter your equation: ");

    String s=input.next();

    if(s.equals("quit")){
        System.out.println("Thank you for using my program!");
        System.exit(0);
    }

    numA = Double.parseDouble(s);
    operator = input.next().charAt(0);
    numB = input.nextDouble();        

    if (operator == '+') {
        answer = maths.add(numA, numB);
    }

    if (operator == '-') {
        answer = maths.subtract(numA, numB);
    }

    if (operator == '*') {
        answer = maths.multiply(numA, numB);
    }

    if (operator == '/') {
        answer = maths.divide(numA, numB);
    }

    if (operator == '^') {
        answer = maths.power(numA, numB);
    }

    if (operator == '|') {
        answer = Math.abs(numA);
    }

        System.out.println(answer);        



        }

    }

}

class Maths {

    double add(double a, double b) {
        double answer = a+b;
        return answer;          
    }

    double subtract(double a, double b) {
        double answer = a-b;
        return answer;          
    }

    double multiply(double a, double b) {
        double answer = a*b;
        return answer;          
    }

    double divide(double a, double b) {
        double answer = a/b;
        return answer;          
    }

    double power(double a, double b){
        double answer =a;

        for (int x=2; x<=b; x++){
            answer *= a;
        }

        return answer;
    }

    double absolute(double a) {
        double answer = Math.abs(a);
        return answer;
    }


}

2 个答案:

答案 0 :(得分:1)

我对您现有的代码进行了一些修改,以便它适用于所有情况并允许将来扩展功能。您可以通过评论了解更改。此外,如果用户只为函数提供一个输入,那么代码将能够运行,其中只有单个参数就足够了。我没有改变你的任何功能。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

public class Calculator {

    public static void main(String[] args) {

        System.out.println("Hello, welcome to my calculator");
        System.out.println("Enter in some stuff you want to me to calculate");

        Scanner scan = new Scanner(System.in);
        System.out.println("If you need help please type \"help\"");
        System.out.println("If at anytime you want to leave, type \"quit\"");
        System.out.println("Hit enter to continue.");

        String s1 = scan.nextLine();

        if (s1.equals("help")) {
            System.out.println(" ");

            System.out.println("Double operand commands:");
            System.out.println("Addition: '+' (Ex: 'a + b' )");
            System.out.println("Subtraction: '-' (Ex: 'a - b' )");
            System.out.println("Multiplication: '*' (Ex: 'a * b' ) ");
            System.out.println("Division: '/' (Ex: 'a / b' )");
            System.out.println("Exponents: '^' (Ex: 'a ^ b' )");

            System.out.println(" ");
        } else if (s1.equals("quit")) {
            System.out.println("Thank you for using my program!");
            System.exit(0);
        }

        Scanner input = new Scanner(System.in);


        Maths maths = new Maths();

        double answer = 0;
        double numA=0.0, numB=0.0;
        char operator;
        boolean quit = false;

        while (true) {

            System.out.print("Please enter your equation: ");

            //First scan the function as a string
            String s = input.next();

            if (s.equals("quit")) {
                System.out.println("Thank you for using my program!");
                System.exit(0);
            }

          //We will use regex to find the operator, so we will omit all alphabetic letter or numeric number or decimal
            String operator1 = s.replaceAll("[a-zA-Z0-9.]",""); 
          //For functions like -4|, the operator1 will be -| after replacing through regex, we will only take the second digit as operator to prevent error
            if(operator1.length()==1) 
            operator = operator1.charAt(0);
            else
                operator = operator1.charAt(1); 
            String[] num11 = (s.split("[^0-9,.]"));
        //String array num11 may contain null string after splitting using regex, we will remove those null string and store only variable values in an arraylist
           ArrayList<String> arraylist = new ArrayList<String>();

            for (int i = 0; i < num11.length; i++)
            {
                if (!num11[i].equals(""))
                {
                    arraylist.add(num11[i]);
                }
            }



            if(arraylist.size()==1){
            numA = Double.parseDouble(arraylist.get(0));    
            numB=numA;}
            else if(arraylist.size()==2){
            numA = Double.parseDouble(arraylist.get(0));    
            numB = Double.parseDouble(arraylist.get(1));

            }




            if (operator == '+') {
                answer = maths.add(numA, numB);
            }

            if (operator == '-') {
                answer = maths.subtract(numA, numB);
            }

            if (operator == '*') {
                answer = maths.multiply(numA, numB);
            }

            if (operator == '/') {
                answer = maths.divide(numA, numB);
            }

            if (operator == '^') {
                answer = maths.power(numA, numB);
            }

            if (operator == '|') {
                answer = Math.abs(numA);
            }

            System.out.println(answer);

        }

    }

    public static class Maths {

        public void Maths(){};

        double add(double a, double b) {
            double answer = a + b;
            return answer;
        }

        double subtract(double a, double b) {
            double answer = a - b;
            return answer;
        }

        double multiply(double a, double b) {
            double answer = a * b;
            return answer;
        }

        double divide(double a, double b) {
            double answer = a / b;
            return answer;
        }

        double power(double a, double b) {
            double answer = a;

            for (int x = 2; x <= b; x++) {
                answer *= a;
            }

            return answer;
        }

        double absolute(double a) {
            double answer = Math.abs(a);
            return answer;
        }

    }

}

<强>输出:

Please enter your equation: +4+4
8.0
Please enter your equation: 4+4
8.0
Please enter your equation: 4+3
7.0
Please enter your equation: 4-3
1.0
Please enter your equation: 4/3
1.3333333333333333
Please enter your equation: -4|
4.0
Please enter your equation: 4|
4.0
Please enter your equation: 3^2
9.0

答案 1 :(得分:0)

使用正则表达式检查第一个数字是否实际上是一个数字。然后做你想做的事情。此外,您可以使用常规异常处理错误的用户输入。如果您输入&#34; 3 + 3&#34;

,您将无法获得java.lang.NumberFormatException s
if (s.matches("^[-+]?[0-9]*\\.?[0-9]+$")) { //Check whether first number is actually a number
    numA = Double.parseDouble(s);
    operator = input.next().charAt(0);
    numB = input.nextDouble();

} else {
    operator = s.charAt(0);
    numA = input.nextDouble();
    numB = 0;
}