Results 1 to 4 of 4
Thread: Another problem
- 04-20-2012, 04:49 AM #1
Member
- Join Date
- Apr 2012
- Posts
- 19
- Rep Power
- 0
Another problem
Hello, I am back, I got another issue, please help out :)
I am suppose to return the number REVERSED (EX. 123456 -> 654321), which is the value a, any help here?Java Code:import javax.swing.JOptionPane; public class Original_16 { public void init() { String number; int a; a = Integer.parseInt(JOptionPane.showInputDialog ( " Enter the a 5-digit #: " )); System.out.println(hello(a)); } public int hello(int x) { int remainder; while (x>0) { remainder = x%10; x = x/10; } } return remainder; }
- 04-20-2012, 11:02 AM #2
Re: Another problem
How would you do that on paper? Write down the steps and identify the mathematical operations involved.
Then write Java code that performs the same mathematical operations.
dbWhy do they call it rush hour when nothing moves? - Robin Williams
- 04-20-2012, 11:50 PM #3
Member
- Join Date
- Apr 2012
- Posts
- 19
- Rep Power
- 0
Re: Another problem
Printing it out is easy, but I could figure out how to return the value, am I suppose to write a for loop for it?
- 04-21-2012, 02:04 AM #4
Senior Member
- Join Date
- Apr 2012
- Location
- New York State of Confusion, USA
- Posts
- 137
- Blog Entries
- 1
- Rep Power
- 0
Re: Another problem
Why does this have to be a mathematic process? Why can't you just treat it like a string of characters (they happen to be digits)? Trim leading and trailing blanks (look at the methods String provides), and work through the string one position at a time? Yes, you can certainly use a for loop. String has methods to get a character at a specific position, that tell you the length of the string and also to turn a String into a character array, not to mention many other useful methods.
Unless you need to perform mathematic operations on the result, I see not reason to go through such unnatural extents to reverse that number. Even if you need the result as a numeric type in the end, you can use the same technique you used to turn the input string into a number.


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks