当我只在一行中输入 1 或 2 个整数时,我的程序可以正常工作,例如:+ 13 24 或 * 4 - 165 235。但如果我输入 % * 5 12 8,它不会给我正确的答案。我怎样才能改变我的循环,以便它在连续有更长的整数字符串时工作。给定前缀符号的操作顺序和格式?*我的堆栈类及其方法确实可以正常工作。
import java.util.*;
public class part1Main {
public static void main(String[] args) {
// Reference variables
String temp2;
int num, num1, num2, ch;
char op;
@SuppressWarnings("resource")
Scanner keyboard = new Scanner(System.in);
PrefixStack<Character> operands = new PrefixStack<Character>();
PrefixStack<Integer> S = new PrefixStack<Integer>();
System.out.print("Do you want to perform a prefix operation?");
System.out.print(" 1 for yes or 0 to quit: ");
ch = keyboard.nextInt();
temp2 = keyboard.nextLine();
while(ch != 0){
System.out.print('\n'+ "Enter the operation with a space between "
+ "each character. End your operation with a period: ");
while(keyboard.hasNext()){
if (keyboard.hasNextInt()){
num = keyboard.nextInt();
S.push(num);}
else{
temp2 = keyboard.next();
switch(temp2.charAt(0)){
case '+': operands.push('+');
break;
case '-': operands.push('-');
break;
case '/': operands.push('/');
break;
case '*': operands.push('*');
break;
case '%': operands.push('%');
break;
}
}
if(temp2.charAt(0) == '.')
break;
}
while(S.size > 1){
op = operands.pop();
num2 = S.pop();
num1 = S.pop();
switch(op){
case '+': S.push(num1 + num2);;
break;
case '-': S.push(num1 - num2);;
break;
case '/': S.push(num1 / num2);;
break;
case '*': S.push(num1 * num2);;
break;
case '%': S.push(num1 % num2);
break;
}
}
System.out.println("Your operation = " + S.pop());
System.out.print('\n'+"Do you want to perform another operation?");
System.out.print(" 1 for yes or 0 to quit: ");
ch = keyboard.nextInt();
}
}
}