Say A user inputs the following 100 + 12 - 1 / 3 Using Scanner, I get that input and then split it to 100,+,12,-,1,/3 Now what I want to do is calculate the total in the order provided. 112 then 111 then 37 so the answer is 37.
This is my current thought process but now I'm stuck on how to implement it in Java for the rest of the length and operators.
This only work for "1 + 1" or "1 / 1" But what I need is for some variable to hold the first 2 integers result and then -,*,/ or add based on the rest of the expression.
Scanner numstr = new Scanner(System.in);
String input = numstr.nextLine();
String [] str = input.split(" ");
int sum =0;
int add =0;
int temp;
for (int i=0;i<str.length;i++) {
if (i%2 >0 && str[i].equals("+"))
{
sum = Integer.parseInt(str[i-1]) + Integer.parseInt(str[i+1]);
//sum = add;
System.out.println(sum);
}
temp =sum;
else if (i%2 >0 && str[i].equals("-"))
{
sum = Integer.parseInt(str[i-1]) - Integer.parseInt(str[i+1]);
//sum = temp - Integer.parseInt(str[i+1]);
System.out.println(sum);
}
//temp = sum;
else if (i%2 >0 && str[i].equals("/"))
{
sum = Integer.parseInt(str[i-1]) / Integer.parseInt(str[i+1]);
System.out.println(sum);
}
else if (i%2 >0 && str[i].equals("*"))
{
sum = Integer.parseInt(str[i-1]) * Integer.parseInt(str[i+1]);
System.out.println(sum);
}
else if (i%2 >0 && !str[i].equals("+")&&!str[i].equals("-")&&!str[i].equals("/")&&!str[i].equals("*"))
{
System.out.println("unknow operator");
}
}
so for 1 + 2 + 5 * 30 would be: 3, 8, 240