Search code examples
javareversecharat

Reversing a String from user's input


I have written code to prompt user to input a sentence which will be displayed reversed by the system. I have managed it with a bit of help, but I now struggle to comment my codes to explain each piece of it. I somewhat understand what I have done, but I feel like I do not master the "whys" of each line.

Anyone able to help with my comments ?

public static void main(String[] args) {
    // TODO Auto-generated method stub

    String original = "", reverse = ""; // Setting the strings values
    Scanner in = new Scanner(System.in); // Scanner is equal to input from user

    while(!original.contains("exit"))
    // As long as user does not input "exit", user will be prompt to enter a sentence
    {
        original = "";
        reverse = "";
        System.out.println("Enter a sentence to be reversed: ");
        original = in.nextLine(); // Setting "original" to be equal to user's input

        int length = original.length(); // Getting user's input character length (original)
        for (int i = length - 1; i >= 0; i--) // Getting input from the last character to be reversed
        reverse = reverse + original.charAt(i); //Setting "reverse" to the input "original" characters

        System.out.println(reverse); // Printing the input reversely
    }

}

Most blurry parts being the:

for (int i = length - 1; i >= 0; i--)

and the:

reverse = reverse + original.charAt(i);

Solution

  • Here's an explanation of what's happening.

    public static void main(String[] args) {
        String original = "", reverse = ""; // Create empty variables to hold the input and output
        Scanner in = new Scanner(System.in); // Create an object to read from StdIn
    
        while(!original.contains("exit"))
        // Read from StdIn as long as user does not input "exit"
        {
            original = "";
            reverse = "";
            System.out.println("Enter a sentence to be reversed: ");
            original = in.nextLine(); // Save the user's input as "original"
    
            int length = original.length(); // Get the length of the input
            for (int i = length - 1; i >= 0; i--) // Iterate over each character of the input, starting from the end until you reach the beginning and add the character to the "reverse" string
            reverse = reverse + original.charAt(i); 
    
            System.out.println(reverse); // Output the result
        }
    }
    

    Having two separate comments to explain the for loop doesn't make much sense as each of the two lines are meaningless without the other.