Reputation: 13
I'm making a calculator for my java class, where we have to input a left operand, choose an operator from a menu of 5 choices (where one is to exit) and choose a right operand. It's supposed to keep asking for an operator from the menu and a right operand until the user selects 5 (the exit choice) and save the "resultSoFar" as the left operand so it could keep going on and on.
At the end, the program is supposed to print the whole summation. So, for example, an end result could look like "3 / 4 + 6 - 2 = whatever" (didn't bother with the math). Don't worry that it doesn't do it in order, it's still early in the class and the teacher doesn't mind.
I can't figure out how to get it to save the individual inputs so they can be printed at the end. Here's the code:
import java.util.Scanner;
public class JavaAssignment5
{
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
String operator = "";
double leftOp = 0.0;
double rightOp;
double resultSoFar = leftOp;
System.out.print("Please choose the left operand : ");
leftOp = stdIn.nextDouble();
System.out.println();
while (!(operator.equals("1") || operator.equals("2") || operator.equals("3") || operator.equals("4") || operator.equals("5")))
{
System.out.println("1 -> Multiplication");
System.out.println("2 -> Division");
System.out.println("3 -> Addition");
System.out.println("4 -> Subtraction");
System.out.println("5 -> Exit");
System.out.println();
while (!(operator.equals("1") || operator.equals("2") || operator.equals("3") || operator.equals("4") || operator.equals("5")))
{
System.out.println("Please choose a operator from the menu above : ");
String throwAway = stdIn.nextLine();
operator = stdIn.nextLine();
}
System.out.println("Please choose a right operand : ");
rightOp = stdIn.nextDouble();
if (operator.equals("1"))
{
resultSoFar = leftOp * rightOp;
}
if (operator.equals("2"))
{
resultSoFar = leftOp / rightOp;
}
if (operator.equals("3"))
{
resultSoFar = leftOp + rightOp;
}
if (operator.equals("4"))
{
resultSoFar = leftOp - rightOp;
}
}
System.out.println(resultSoFar);
}
}
Upvotes: 1
Views: 157
Reputation: 159086
If all you need is to display the final equation (e.g. 3 / 4 + 6 - 2
), then build up that String in a single StringBuilder
as you go.
If you need the individual values and operators at the end, then two ArrayList
objects would suffice, one for the values, and one for the operators. Lists are good for collecting values of unknown length, because, unlike arrays, they can grow in size.
If you're getting to the point of implementing operator precedence, then an expression tree needs to be built, but it sounds like you're not there yet.
Upvotes: 2