Calculator in java [closed]

时光怂恿深爱的人放手 提交于 2019-12-02 18:50:14

问题


Lately I've worked on simple calculator that can add, substract, multiply and divide.

public static void main(String arr[]){ 
    double num1, num2;
    String ans = null;

    System.out.println("Calculator manu:");
    System.out.println("\n"+"a for adding"); 
    System.out.println("b for substracting");
    System.out.println("c for multiplying");
    System.out.println("d for dividing");

    Scanner NumInput = new Scanner(System.in);

    System.out.println("\n"+"Enter number one: ");
    num1 = NumInput.nextDouble();

    System.out.println("\n"+"Enter number two: ");
    num2 = NumInput.nextDouble();

    while(true)
    {   
    Scanner AnsInput = new Scanner(System.in);
    System.out.println("\n"+"Choose operation.");
    String answer = AnsInput.next();


    if(AnsInput.equals("1"))
    {
        answer = Double.toString(num1+num2);
        System.out.println("\n"+"The sum of the first and second number is: "+answer);
    }
    else if(AnsInput.equals("2")) 
    {
        answer = Double.toString(num1-num2);
        System.out.println("\n"+"Subtraction of the first and the second number is: "+answer);
    }
    else if(AnsInput.equals("3"))
    {
        answer = Double.toString(num1*num2);
        System.out.println("\n"+"The product of the first and second number is: "+answer);
    }
    else if(AnsInput.equals("4"))
    {
        answer = Double.toString(num1/num2);
        System.out.println("\n"+"Ratio of the first and the second number is: "+answer);
    }
    }
}

But what if I want to wright program that works like an ordinary calculator; it adds, subtracts, multiplies, divides, ... ,but not only whit two but multiple numbers.


回答1:


This can certainly be done! Although it requires substantial framework. However, if you want to use this type of simplistic code, what you need to do is store the numbers somewhere else, outside this function, and every two numbers you apply an operation to, you store it and use it as the first argument along the third you wanted to use. And so on. Does this make sense?



来源:https://stackoverflow.com/questions/20290991/calculator-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!