Java 有人能解决用堆栈计算算术表达式时的错误吗?
我编写了一个代码,可以读取字符串形式的任何算术表达式,并通过打印返回结果。Java 有人能解决用堆栈计算算术表达式时的错误吗?,java,math,stack,Java,Math,Stack,我编写了一个代码,可以读取字符串形式的任何算术表达式,并通过打印返回结果。 所有这些都是根据操作顺序(PEMDAS)完成的。 例如,输入“2+7*5+3”应返回40 但问题是程序没有返回正确的结果,我不知道问题出在哪里。 守则: public class LL { public static int calc(String op, int n1,int n2){ if(op.equals("+")){ return n1+n2;
所有这些都是根据操作顺序(PEMDAS)完成的。 例如,输入“2+7*5+3”应返回40 但问题是程序没有返回正确的结果,我不知道问题出在哪里。
守则:
public class LL {
public static int calc(String op, int n1,int n2){
if(op.equals("+")){
return n1+n2;
}
else if(op.equals("-")){
return n1-n2;
}
else if(op.equals("/")){
return n1/n2;
}
else{
return n1*n2;
}
}
public static boolean check(String oldop, String newop){
if(oldop==null||oldop.equals("=")){
return true;
}
else if(oldop.equals("+")||oldop.equals("-")){
if(newop.equals("+")||newop.equals("-")||newop.equals("/")||newop.equals("*")){
return true;
}
else{
return false;
}
}
else{
if(newop.equals("/")||newop.equals("*")){
return true;
}
else{
return false;
}
}
}
public static void main(String[] args) {
int ch=0;
LinkedList<String> op = new LinkedList<String>();
LinkedList<String> nums = new LinkedList<String>();
Scanner sc = new Scanner(System.in);
String exp = sc.nextLine();
String[] exparr = exp.split(" ");
for(int i = 0 ; i<exparr.length-1;i+=2){
nums.push(exparr[i]);
String oldop = op.pop();
if(check(oldop,exparr[i+1])){
if(oldop!=null)
op.push(oldop);
op.push(exparr[i+1]);
}
else{
String n2=nums.pop();
String n1=nums.pop();
int nn2=Integer.parseInt(n2);
int nn1=Integer.parseInt(n1);
int res = calc(oldop,nn1,nn2);
nums.push(Integer.toString(res));
op.push(exparr[i+1]);
}
}
nums.push(exparr[exparr.length-1]);
String opp = op.pop();
while(opp!=null){
String n2=nums.pop();
String n1=nums.pop();
int nn2=Integer.parseInt(n2);
int nn1=Integer.parseInt(n1);
int res = calc(opp,nn1,nn2);
nums.push(Integer.toString(res));
opp = op.pop();
}
System.out.println(nums.pop());
}
}
公共类LL{
公共静态整数计算(字符串op,整数n1,整数n2){
if(op.equals(“+”)){
返回n1+n2;
}
else if(op.equals(“-”)){
返回n1-n2;
}
else if(op.equals(“/”){
返回n1/n2;
}
否则{
返回n1*n2;
}
}
公共静态布尔检查(字符串oldop、字符串newop){
如果(oldop==null | | oldop.equals(“=”)){
返回true;
}
else if(oldop.equals(“+”)| | oldop.equals(“-”){
if(newop.equals(“+”)| newop.equals(“-”)| newop.equals(“/”)| newop.equals(“*”){
返回true;
}
否则{
返回false;
}
}
否则{
if(newop.equals(“/”)| | newop.equals(“*”){
返回true;
}
否则{
返回false;
}
}
}
公共静态void main(字符串[]args){
int ch=0;
LinkedList op=新建LinkedList();
LinkedList nums=新建LinkedList();
扫描仪sc=新的扫描仪(System.in);
字符串exp=sc.nextLine();
字符串[]exparr=exp.split(“”);
对于(int i=0;i您的检查方法是错误的。如果旧操作是+或-,则必须返回true,而新操作是*或/否则返回false
public static boolean check(String oldop, String newop){
if(oldop == null || oldop.equals("=")){
return true;
}
return (oldop.equals("+") || oldop.equals("-")) && (newop.equals("/") || newop.equals("*"));
}
另一点是,不要使用LinkedList的pop
方法,如果列表为空
,此方法会引发异常
,如果列表为空,请使用poll
方法返回null
另一个代码是正确的