gpt4 book ai didi

java - 使用堆栈声明编译错误

转载 作者:行者123 更新时间:2023-12-02 11:04:26 25 4
gpt4 key购买 nike

因此,我是Java的新手,我正在尝试制作一个具有一些典型错误控制的计算器,但似乎无法正常工作,而且有点卡住了。对于造成故障的原因,我非常感谢您的帮助。编译器给我这个

Exception in thread "main" java.util.EmptyStackException
at java.util.Stack.peek(Stack.java:102)
at ergasia.ioanna.ErgasiaIoanna.check(ErgasiaIoanna.java:38)
at ergasia.ioanna.ErgasiaIoanna.main(ErgasiaIoanna.java:101)
Java Result: 1
BUILD SUCCESSFUL (total time: 3 seconds)
package ergasia.ioanna;

import java.util.*;
import java.io.*;

public class ErgasiaIoanna {

static void praksi(Stack telestes,Stack arithmoi){
double res;
Character temp = (Character) telestes.pop();
Double ar2 = (Double) arithmoi.pop();
Double ar1 = (Double) arithmoi.pop();
if(temp=='+'){
res=ar1+ar2;
}
if(temp=='-'){
res=ar1-ar2;
}
if(temp=='*'){
res=ar1*ar2;
}
if(temp=='/'){
if(ar2==0){
System.out.println("error");
}
else{
res=ar1/ar2;
}
}
if(temp=='^'){
res=Math.pow(ar1,ar2);
}
arithmoi.push( new Double (res) );

}
static void check(char i,Stack telestes,Stack arithmoi){
int error=0;
char cha = (Character) telestes.peek();
double ar = (Double) arithmoi.peek();
if(i==')'){
if(telestes.empty() || cha=='('){
System.out.println("error");
error=1;
}
do{
praksi(telestes,arithmoi);
cha=(char) telestes.peek();
if(telestes.empty()){
System.out.println("error");
cha='(';
}
}while(cha!='(');
}
if(i=='='){
while(!telestes.empty()){
praksi(telestes,arithmoi);
cha = (Character) telestes.peek();
}
System.out.print(arithmoi.pop());
}
if(i=='+' || i=='-'){
if(!telestes.empty() || cha!='('){
praksi(telestes,arithmoi);
telestes.push(i);
}
else{
telestes.push(i);
}
}
if(i=='*' || i=='/'){
if(cha=='^'){
praksi(telestes,arithmoi);
telestes.push(i);
}
else{
telestes.push(i);
}
}
if(i=='^'){
if(!telestes.empty() || cha!='('){
praksi(telestes,arithmoi);
telestes.push(i);
}
else{
telestes.push(i);
}

}
}



public static void main(String[] args)throws IOException {
Stack Tel = new Stack();
Stack Ar = new Stack();
char c;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
do {
c = (char) br.read();
check(c,Tel,Ar);
} while(c != 's');
}
}

最佳答案

java.util.EmptyStackException异常表示您正在尝试操作,在这种情况下为空堆栈上的peek。在main方法中,您声明了两个StackTelAr。两者都开始是空的。然后,您将这些空堆栈传递给check方法,该方法尝试在其第一个元素(即获得peek)的位置进行EmptyStackException

关于java - 使用堆栈声明编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21969603/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com