I'm trying to get only one input from the user and do the calculation with the previous result. The calculator starts at 0
, although I know there could be some problems for multiplication. For now that is not important. I've been stuck with this for a while and I can't seem to find a solution for it. So this would look something like this:
0
+ 3 (user input)
3 (result)
- 2 (user input)
1 (result)
The code does that a couple of times but I need a loop somehow so that it does that until the user says something like exit
or e
or something else.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Please enter your calculation");
Scanner scanner = new Scanner(System.in);
System.out.println("0");
//int left = scanner.nextInt();
String op = scanner.next();
int right = scanner.nextInt();
int num3 = compute(0,op,right);
System.out.println(num3);
int rright;
int rrright;
System.out.println("Enter your calculation");
String op1 = scanner.next();
rright = scanner.nextInt();
int num4 = compute(num3,op1,rright);
System.out.println(num4);
System.out.println("Enter your calculation");
String op2 = scanner.next();
rrright = scanner.nextInt();
int num5 = compute(num4,op2,rrright);
System.out.println(num5);
}
private static int compute(int left, String op, int right) {
switch (op.charAt(0)) {
case '+':
return left + right;
case '-':
return left - right;
case '*':
return left * right;
case '/':
return left / right;
}
throw new IllegalArgumentException("Unknown operator:" + op);
}
}