A Program With StringTokenizer in Java

A Program With StringTokenizer in Java

Assuming your input is correct the following might help you (if you have more operators just append to the list). The true in the parameter means you want to use the given operator as a delimiter as well as an operator, meaning it will be returned as a token too.

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

    }
}

NOTE: try to use another option mentioned in the comments instead of StringTokenizer if you have not to.

A Program With StringTokenizer in Java

Leave a Reply

Your email address will not be published. Required fields are marked *