So, we made this in our first semester. Why is it removing the 0 in the end? And how do I fix it? I input 4000 and it showed me 4, when I needed is 4 0 0 0. Same if I input 8030, it outputs 8 0 3.
if (number > 0) {
while (number != 0) {
individualNum = individualNum * 10 + number % 10;
number = number / 10;
}
while (individualNum > 0) {
System.out.print((individualNum % 10));
sum = sum + (individualNum % 10);
individualNum = individualNum / 10;
if (individualNum > 0) {
System.out.print(" ");
}
else if (individualNum < 0){
System.out.print((individualNum ));
sum = sum + (individualNum % 10) * -1;
individualNum = individualNum / 10;
}
}
System.out.println(" = " + sum);
}
else if (number < 0){
while (number != 0) {
individualNum = individualNum * 10 + number % 10;
number = number / 10;
}
while (individualNum < 0) {
System.out.print((individualNum*-1 % 10));
sum = sum + (individualNum % 10);
individualNum = individualNum / 10;
if (individualNum < 0) {
System.out.print(" ");
}
else if (individualNum < 0){
System.out.print((individualNum ));
sum = sum + (individualNum % 10) ;
individualNum = individualNum / 10;
}
}
System.out.println(" = " + sum * -1 );
}
}catch (InputMismatchException x ){
System.out.println("Please enter the negative sign at the front");
}
}
}
If I understand your code correctly your goal is to list the individual digits and print their sum. To that end, you're first calculating the "inverse" of your input number as
individualNum, i.e. if your input was8030you'd expect to get0308. However, note that integers don't have leading zeros so you actually get308(or in the case of 4000 just4).That's where your trailing zeros are lost.
To fix this you need to use
numberin your second loop again, but since you've reduced it to 0 in the first loop that doesn't work. Solution? Make a copy first.It also looks like you want to tread negative numbers the same, i.e. -8030 should still print
8 0 3 0 = 11. In that case you should negate any negative numbers first, e.g.Ideally use a copy of
numberso you can retain your initial input.