Jared Trujillo
Jared Trujillo

Reputation: 5

How to reverse integers using while or for loop

Sorry, I am new to java. I want to create a program that displays reversed integers using any kind of loop. For example I would ask user to enter a positive integer and then I would return reversed input to the user. So far this is the closest I got, but I get the count of the string in reverse and not the values that were captured.

String number;

for (int c = number.length(); c >= 0; c--) {
    System.out.print(c);
}

Upvotes: 0

Views: 180

Answers (2)

Vishal Gajera
Vishal Gajera

Reputation: 4207

You can try something likewise(either of way),

public static void main(String[] args) {
        String number = "hello";

        for (int c = number.length()-1; c >= 0; c--)
        {
            System.out.print(number.charAt(c));
        }
        // At the end output is : olleh

        System.out.println();
        // Or another way is, using StringBuffer
        StringBuffer sb = new StringBuffer("Hello String");
        System.out.println(sb.reverse()); //Output :- gnirtS olleH

    }

Upvotes: 2

Kevyn Meganck
Kevyn Meganck

Reputation: 609

String number;

for (int c = number.length() - 1; c >= 0; c--){
    System.out.print(number.charAt(c));
}

This should do the trick. c is the position in your string, use it to print the char at that position. (Also, remember it's String, not string. Same for System)

Edit: Oops, forgot to add the "-1" in number.length()

Upvotes: 2

Related Questions