Jump to content

Am I doing something wrong with my print statement?

Featured Replies

Hi guys I am not sure why my output is not printing the original number that the user inputs instead it prints 0.

 

For example, if the user enters the number 226689, the expected out put is supposed to show:

Enter a number to be reversed:The reverse of 226689 is 986622

 

However, my output shows:

Enter a number to be reversed:The reverse of 0 is 986622

 

Here's my code:

 

import java.util.Scanner;

public class ReverseDigits {
public static void main ( String args[] ) {
ReverseDigits reversal = new ReverseDigits();
reversal.reverseNumber ();
}
public void reverseNumber() {
Scanner input = new Scanner (System.in);
int num;
int digit;
int rev = 0;
System.out.printf("Enter a number to be reversed:");
num = input.nextInt ();
while(num != 0) {
digit = num % 10;
rev = rev * 10 + digit;
num /= 10;
}
System.out.printf("The reverse of %d is %d", num, rev);
}
}

You're dividing num by 10 every loop execution, until it's 0.

Then you're showing num, which is obviously 0.

Make spare variable int num2 = num; and show it instead.

Archived

This topic is now archived and is closed to further replies.

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.