Need Help with simple Java Program

lestat

Senior member
Oct 9, 1999
767
0
0
I am having trouble of thinking of good ways to do this program. Basically all I have to do is get an integer and print it out backwards. Is there a way to convert a int to a string? A sample output would work like this:

Please enter in a number: 12345

5 4 3 2 1

We don't even have to get it from the user, but I want to because its kind of crappy to have to change it every time you want to use a different number. The way they wanted us to do it was with modulus and division operations, which is alright, but is there another way anyone knows of?

Thankee
 

Jumpem

Lifer
Sep 21, 2000
10,757
3
81
Save each digit as a single charcter into a stack and then pop each character out and print it.

For example, input is 12345

Here's the stack with characters in it, now just pop and print.

| |
| |
| 5 |
| 4 |
| 3 |
| 2 |
| 1 |
 

GiLtY

Golden Member
Sep 10, 2000
1,487
1
0
If you don't need to do any calculations with them, Jumpem's idea is good. Make a character/interger array with one number in each cell. Then use a for loop to count it backwards, should do the trick.
 

eLiu

Diamond Member
Jun 4, 2001
6,407
1
0
you could input them into an array...then print out the array counting backwards...(easiest way imo)

but the stack idea is neat too
 

Ameesh

Lifer
Apr 3, 2001
23,686
1
0
or you can do it something like this:


//asumming base 10 number system
//this should compile in java or c


int reverse(int input)
{
int temp = 0;
if( input == 0 )
return(0);
while( input != 0)
{
temp = (temp * 10) + (input % 10);
input = input /10;
}
return temp;
}
 

rutchtkim

Golden Member
Aug 2, 2001
1,880
0
0
Well this is how I would do it from a file.

void reverseList(BufferedReader br) throws IOException{
String s=br.readLine();
if(s==null)return;
reverseList9br);
S.O.P(s);
}

thanks for the hint ameesh