0
所以我是新來的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');
}
}
這不是編譯錯誤。這是您程序的運行時錯誤。添加一些調試打印或通過調試器運行你的程序來找出錯誤。 –