Jump to content

Recommended Posts

Posted

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);
}
}
Posted

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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

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.