Reversing a number in Java

I have a lot of experience with C++. So while learning about if-else statements and loops is interesting, it’s essentially the same between C++ and Java. That being said, I think the best way to learn a programming language is to just write code in that language. So I’ve looked around for examples online and I found a few decent tutorial sites. The following code is taken from the second last site linked in the previous sentence, and the purpose of the code is to reverse a number (so 34 would become 43, 57 would become 75, etc.).

I don’t want to just copy the code from this example, but I did need to look up how to take user input. It seems like the easiest way is with java.util.Scanner, which can read in single variables or lines of text from the command line. Also, I wanted to look up how to construct Strings, because I wanted to avoid a case where “90” might be reversed to “9” instead of “09”. I want the output to be a String, not an integer.

import java.util.Scanner;

public class ReverseNumber {

  public static String reverseIt(int oldInt){

    String newInt = "";
    newInt += oldInt%10;
    newInt += (oldInt - (oldInt%10))/10;
    return newInt;

  }

  public static void main(String args[]){

    Scanner userInt = new Scanner(System.in);

    System.out.println("Enter any number between 10 and 99: ");
    int myInt = userInt.nextInt();

    System.out.println("You entered: " + myInt);
    System.out.println("Reversed, that is: " + reverseIt(myInt));

  }

}

…it works! Strings are pretty easy to work with in Java, too. And since they’re a basic data type, no extra packages need to be included. This is in stark contrast to C++, where strings are more complex and a bit more difficult to work with. Strings can also be constructed with a StringBuilder() object or using String.format() for a more C-style look.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s