I am designing a simple calculator using Java but I can't seem to make it work. I'm new at programming I tried everything on scanning every line.
The output I am trying to get is when I input 1 + 1 I need to get the output of 2 and I want to implement the MDAS rule which the multiplication and division has higher precedence over addition and subtraction.
Specific output is:
Enter: 2+1=
index= 0
2
index= 1
1
2
import java.util.*;
import java.lang.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.lang.Throwable.*;
public class Final{
public static void main(String[]args){
Scanner in = new Scanner (System.in);
System.out.print("Enter: ");
String text = in.nextLine();
int pipe[] = new int [text.length()];
int index = 0;
for(int i =0; i < text.length(); i++) {
if (text.charAt(i) == (int) ' ' || text.charAt(i) == (int) '\t')
; // strip out white spaces
else if (Character.isDigit(text.charAt(i))) {
int n = 0;
do {
n = n * 10 + text.charAt(i) - (int) '0';
i++;
}
while (Character.isDigit(text.charAt(i)));
pipe[index] = n;
System.out.println("index= " + index);
System.out.println(pipe[index]);
index ++;
} else if (text.charAt(i) == '+') {
System.out.println("index= " + index);
System.out.println("+");
pipe[index-2] = pipe[index-2] + pipe[index-1];
System.out.println("r: " + pipe[index-2]);
index = index - 1;
} else if (text.charAt(i) == '-') {
System.out.println("index= " + index);
System.out.println("-");
pipe[index-2] = pipe[index-2] - pipe[index-1];
System.out.println("r: " + pipe[index-2]);
index = index - 1;
} else if (text.charAt(i) == '*') {
System.out.println("index= " + index);
System.out.println("*");
pipe[index-2] = pipe[index-2] * pipe[index-1];
System.out.println("r: " + pipe[index-2]);
index = index - 1;
} else if (text.charAt(i) == '/') {
System.out.println("index= " + index);
System.out.println("/");
pipe[index-2] = pipe[index-2] / pipe[index-1];
System.out.println("r: " + pipe[index-2]);
index = index - 1;
}
}
System.out.print(pipe[0]);
}
}