Object-Oriented Programming with Java, part I – Exercise 52

This program takes a string input by the user and then outputs it in reverse order.

My Code

import java.util.Scanner;

public class ReversingName {

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        System.out.print("Type your name: ");
        String name = reader.nextLine();
        System.out.print("In reverse order: ");

        int i = name.length() -1;

        while (i > -1) {
            System.out.print(name.charAt(i));
            i--;
        }
        System.out.println("");
    }
}

Model Code

import java.util.Scanner;

 

public class ReversingName {

    public static void main(String[] args) {

        Scanner reader = new Scanner(System.in);

        System.out.print("Type your name: ");

        String name = reader.nextLine();

        System.out.print("In reverse order: ");

        

        int i = name.length() - 1;

        while (i >= 0) {

            System.out.print(name.charAt(i));

            i--;

        }

        System.out.println("");

    }

}

Comments

My code is the same as the model code.

Leave a comment