-1

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);
Matt
  • 3,052
  • 1
  • 17
  • 30
Jon
  • 19
  • 1
  • 5
  • 3
    Use a debugger and step through your code with a small test input. – jrook Nov 19 '19 at 21:23
  • `For loop**` - Looping over each character of the string starting from last character of the string. `reverse**` - appending each char to form new string. I would suggest to use `StringBuilder` instead of using `String concatenation`. – Swaraj Nov 19 '19 at 21:26

3 Answers3

1

Well, let's look at it with the word 'HELLO' as input. You can tell, that the length of the string is 5, and the first letter (H) has the index 0, the second letter 1, ... and the last one has the index 4, which btw. is length -i. The loop for (int i = length - 1; i >= 0; i--) starts with the last letter, then it takes the second last, and so on, and appends every letter in a reverse order to the reverse string. In general in the loop you will do following:

  • reverse = reverse + original.CharAt(4) => reverse='O'
  • reverse = reverse + original.CharAt(3) => reverse='OL'
  • reverse = reverse + original.CharAt(2) => reverse='OLL'
  • reverse = reverse + original.CharAt(1) => reverse='OLLE'
  • reverse = reverse + original.CharAt(0) => reverse='OLLEH'
agim
  • 1,841
  • 12
  • 19
  • thank you, the length - 1 was slightly confusing even though my understanding was not far from the truth. This is very helpful. Thanks ! – Jon Nov 20 '19 at 15:42
  • If it was helpful, you might consider to vote up this answer, that's actually the idea behind stack overflow. – agim Nov 21 '19 at 15:19
  • 1
    HI @agim, apologies, didn't mean to be disrespectful, I'm starting to use this platform, as I am beginning Java as well. Not familiar with all this. Thanks again. – Jon Nov 21 '19 at 18:02
1

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.

annedroiid
  • 6,267
  • 11
  • 31
  • 54
0

Understanding

for (int i = length - 1; i >= 0; i--)
reverse = reverse + original.charAt(i);

Which you should reformat to look like

for (int i = length - 1; i >= 0; i--)
    reverse = reverse + original.charAt(i);

or

for (int i = length - 1; i >= 0; i--) {
    reverse = reverse + original.charAt(i);
}

means to take what is currently stored in the reverse variable and adding a new character at the end + original.charAt(i). This produces a new String which gets assigned back to the reverse variable, overriding what was in it before like @agim mentioned in his answer.

Here are some other alternatives you could consider. Especially with using StringBuilder because it has a reverse() function built into it, if you're wanting to reverse the sentence by character.

import java.util.*;

public class JavaFiddle
{
  public static void main(String[] args)
  {
    String sentence = "The quick brown fox jumps over the lazy dog";

    // Print sentence forward
    System.out.println(sentence);

    // Print sentence backwards by words
    String[] words = sentence.split(" ");
    for (int i = words.length - 1; i >= 0; i--) {
      System.out.print(words[i] + " ");
    }
    System.out.println();

    // Print sentence backwards by character
    for (int i = sentence.length() - 1; i >= 0; i--) {
      System.out.print(sentence.charAt(i));
    }
    System.out.println();

    // Print sentence backwards by character using StringBuilder;
    StringBuilder reverseSentence = new StringBuilder(sentence);
    System.out.println(reverseSentence.reverse());
  }
}

RESULT

The quick brown fox jumps over the lazy dog
dog lazy the over jumps fox brown quick The 
god yzal eht revo spmuj xof nworb kciuq ehT
god yzal eht revo spmuj xof nworb kciuq ehT
Shar1er80
  • 9,001
  • 2
  • 20
  • 29