FoxyCc87 originally posted:
Hey everyone..I'm trying to code a program in Java that takes an integer, reverses it and outputs the reversed integer using the modulus function. I have my code so far, pasted below, could someone take a look at it and see what is wrong with it?
thanks a bunch!
import java.util.Scanner;
public class ReverseInteger
{
static Scanner input=new Scanner(System.in);
public static int main (String args[])
{
System.out.print("Enter an integer value:");//prompts user to enter an integer value
int userValue = 0;//variable that holds users' input
userValue=input.nextInt();//sets the user input
System.out.print("The reversed number is:" +userValue);
//Method Body
int inputInt = 0;
int reversedInt=0;
int tempInt=0;
while(inputInt>0){
tempInt=inputInt%10;
inputInt=inputInt/10;
reversedInt=(reversedInt*10)+tempInt;
Math.abs(inputInt);
}//end Method body
return reversedInt;
}
}
;)
Firstly, your printed string will output whatever the user specified as the number and not the reversed number.
Secondly, you never said something like inputInt = userInput; because right now...inputInt will always be 0 so it will never go into the loop.
I quickly coded up the exact same thing (minus the reading from the command line) and it works, so here is my code:
Code:
public class ReverseInteger
{
public static void main ( String [] args )
{
int toRev = 123456; /* Arbitrary number to reverse */
int reversed = 0;
while ( toRev > 0 ) /* Loop until the end */
{
int val = toRev % 10; /* Pop off the last digit */
toRev = toRev / 10; /* Shift everything over 1 digit */
reversed = reversed * 10 + val; /* Shift and add */
}
System.out.println ( reversed ); /* Output the reversed number */
}
} This code will output:
654321
Hope this helps,
~juddster