Issue handling the if statement in the String class

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Issue handling the if statement in the String class

Laushkeen

       method void setInt(int j) {
           var int result, lastDigit, g;
           let length = 0;
           if (j < 0) {
               do appendChar(45);
           }
            let j = Math.abs(j);
           if (j < 10) {
               do appendChar(j + 48);
           } else {
                let result = j / 10;
                let lastDigit = j - (result*10);
                do setInt(result);
                do appendChar(lastDigit + 48);
           } 

           return;
       }

I don't understand why if (j < 0) doesn't work. I'm trying to handle negative numbers and it works if I remove if statement, leave just do appendChar(45) or I set it in the end of the method.

See screen: 32767, should be -32767


Reply | Threaded
Open this post in threaded view
|

Re: Issue handling the if statement in the String class

ivant
First of all, we can't see the picture well, it's just this thumbnail.

Run this manually, on a piece of paper and pay attention to the value of the length field. Try it with a single digit number, then with a two and three digit numbers. Then the same with negative numbers.

After fixing those, try with -32767 and with -32768. Hint, compute the two's complement of -32768 as a 16-bit binary number.