Java 中带有 StringTokenizer 的程序

A Program With StringTokenizer in Java

我写了一个简单的计算程序。我希望用户将他们的请求输入为 12+12 和 return 答案。我使用了 StringTokenizer,但出现错误并且没有显示任何结果。有人提到 Calc 是 superclass 而 MinusCalc 和 PlusCalc 是 subclasses。有人知道吗?

    void inputLineData() { // This is just the function that use for this case                                

    System.out.println(" Plz enter your all numbers");
    String strAll = key.next();

    StringTokenizer st = new StringTokenizer(strAll);
    int n1 = Integer.parseInt(st.nextToken());
    String str = st.nextToken();
    int n2 =  Integer.parseInt(st.nextToken());




    switch (str.charAt(0)) {
        case '+':
            PlusCalc P = new PlusCalc(n1, n2);
            listCalc[indexCalc] = P;
            indexCalc++;

            break;
        case '-':
            MinusCalc M = new MinusCalc(n1, n2);
            listCalc[indexCalc] = M;
            indexCalc++;

            break;

        default:
            System.out.println("Error!");

      }

  }

这是 MinusCalc class:

   public class MinusCalc extends Calc {

@Override
public int func(){

    return n1 - n2 ; 
}

public MinusCalc(int n1, int n2) {
    super(n1, n2); 
  }



 }

这是 PlusCalc class:

   public class PlusCalc extends Calc {

 @Override
public int func(){

    return n1 + n2;
}

public PlusCalc(int n1, int n2) {
    super(n1, n2);
  }

}

这是 Calc class:

    public abstract class Calc {

   public Calc(int n1, int n2) { // constructor with parameters!!
    this.n1 = n1;
    this.n2 = n2;
}

int n1,n2;
public abstract int func();

}

假设您的输入是正确的,以下内容可能会对您有所帮助(如果您有更多运算符,只需将其附加到列表中)。参数中的 true 表示您希望将给定的运算符用作分隔符和运算符,这意味着它也将作为标记返回。

StringTokenizer st = new StringTokenizer(strAll, "+-*/", true);
if (st.countTokens() == 3) {
    int operand1 = Integer.parseInt(st.nextToken().trim());
    String operator = st.nextToken();
    int operand2 = Integer.parseInt(st.nextToken().trim());

    switch (operator.charAt(0)) {
        case '+':
            PlusCalc P = new PlusCalc(operand1, operand2);
            listCalc[indexCalc] = P;
            indexCalc++;

            break;
        case '-':
            MinusCalc M = new MinusCalc(operand1, operand2);
            listCalc[indexCalc] = M;
            indexCalc++;

            break;

        default:
            System.out.println("Error!");

    }
}

注意:如果不需要,请尝试使用评论中提到的另一个选项而不是 StringTokenizer