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();
}
答案 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
。