开发者

How can I place numbers at the end of an int (not summing)?

I'm busy with making an expression tree for school, I've already build the part in which the tree is being made and printing the result of the arithmetic expression also works.

There is this extra part to complete the assignment, I'd just like to make that work too. The extra assignment is making the program able to read an expression.

I'm pretty far with this one, but I'm not sure if I coded this thing with placing numbers at the end of an int in a good way. The problem I'm trying to solve is when there is an expression like this...

(3*(8-2))+(12/4)

... how do I get the 12 out of the array of characters since they are two apart characters? I used an array of characters in the rest of the code but of course it's possible to use a String to get the two characters.

I did it this way:

// if the next character is a digit...
if (Character.isDigit(expression[i])) {
    // ... make local variables 'nextNumber'...
    int nextNumber = 0;
    // ... and 'a' which already contains this first digit...
    String a = Character.toString(expression[i]);
    // ... so when we check for the next character... 
    for (int k = i+1; k < expression.length; k++) {
        // ... wether it is a digit,...
        if (Character.isDigit(expression[k])) {
            // ... we can add that digit to 'a',...
            a = a + Character.toString(expression[k开发者_C百科]);
        }
        // ... and if it is not a digit...
        else if (!Character.isDigit(expression[k])) {
            // ... we will exit the for loop.
            break;
        }
    }
    // now we have to change the String to an integer...
    nextNumber = Integer.getInteger(a);
    // ... and then we are sure we have the whole number as it was ment to be
    // in the given expression
    return new ET(nextNumber);
}

But it seems so sloppy. I searched for a long time with Google and all I found was this way but I can't imagine there is no easier or at least a less sloppy way. Do you guys know a better way or is this the way to go?

The solution I build is a relative easy way to solve the problem of the expression tree, I could work it more out but I don't want to spend any more time than is needed as long as I can show the teacher that I understood the lessons. The course which it is for is Algorithmics so it's not really about learning Java, by this I mean that I'm not asking for the solution of the problem the teacher asked me to solve.

Thank you in advance!


You can build up the number digit by digit (pseudocode):

number = 0
for each digit {
    number = number * 10 + value_of(digit)
}

This will yield number as the value of the string of digits (from left to right) in base 10.

In your case: digits = (1,2)

number = 0
number = number * 10 + 1  // <= number = 0*10+1=1
number = number * 10 + 2  // <= number = 1*10+2=12    
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜