我正在使用Java设计一个简单的计算器,但我似乎无法使其工作。我是编程新手,我在扫描每一行时都尝试了一切 我想要得到的输出是当我输入1 + 1时我需要输出2并且我想实现MDAS规则,乘法和除法优先于加法和减法。
具体输出是:
输入: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]);
}
}
答案 0 :(得分:0)
如果你想尊重运算符优先级,你需要一个堆栈,如果自下而上工作,或者一个递归函数自上而下工作。