Results 1 to 4 of 4

Thread: Another problem

  1. #1
    Join Date
    Apr 2012
    Posts
    19
    Rep Power
    0

    Default Another problem

    Hello, I am back, I got another issue, please help out :)

    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;
    }
    I am suppose to return the number REVERSED (EX. 123456 -> 654321), which is the value a, any help here?

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,234
    Rep Power
    19

    Default 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.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  3. #3
    Join Date
    Apr 2012
    Posts
    19
    Rep Power
    0

    Default 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?

  4. #4
    jlczuk is offline Senior Member
    Join Date
    Apr 2012
    Location
    New York State of Confusion, USA
    Posts
    137
    Blog Entries
    1
    Rep Power
    0

    Default 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.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •