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.
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