Java中使用StringTokenizer的程序

时间:2016-07-05 17:37:14

标签: java stringtokenizer

我写了一个简单的计算程序。我希望用户输入他们的请求为12 + 12并返回答案。我使用了StringTokenizer,但是我收到了一个错误,它没有显示任何结果。有人提到Calc是一个超类,MinusCalc和PlusCalc是子类。有没有人有任何想法?

    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课程:

   public class MinusCalc extends Calc {

@Override
public int func(){

    return n1 - n2 ; 
}

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



 }

这是PlusCalc课程:

   public class PlusCalc extends Calc {

 @Override
public int func(){

    return n1 + n2;
}

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

}

这是Calc类:

    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();

}

1 个答案:

答案 0 :(得分:0)

假设您的输入正确,以下内容可能对您有所帮助(如果您有更多运算符只是附加到列表中)。参数中的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