How to reverse order of word in a phrase and reverse the letters in a word?

Viewed 174

Two problems:

  1. In a user-inputted phrase(phrase meaning two or more words with a space between each word), only the last two words are being reversed, and no other words in the phrase are being reversed or even printed.

  2. My code to reverse the order of letters in a word(word meaning a single word) seems to not be printing anything, yet it accepts input endlessly with no results.

Important note: I am barred from using StringBuilder, arrays, or any other "advanced" tools. In fact, it is best that I use only methods that are referenced in the AP Computer Science guidelines(not necessary though). I've tried many things, including adjusting parameters, different concatenations, etc.

I expect the output of "This is a string" to be "string a is this". Instead, it prints "string a". I expect the output of "heck" to be "kceh". Instead, I get nothing.

Note: Comments in code are additional concerns and questions I have, and also meant to help understand my code a bit better. Sorry if it's a bit messy, it's my first time really commenting on my own code.

    Scanner userInput = new Scanner(System.in);

    System.out.print("Enter a word or phrase: ");
    String str = userInput.nextLine();  //user-input string 

    String reversePhrase = "";  //placeholder for reversed phrase
    String reverseWord = "";    //placeholder for reversed word
    char reverseLetter = ' ';   //placeholder for letters in reversed word

    for(int position = 0; position < str.length(); position++)
    {
        if(str.indexOf(" ") > -1)   //checks for space in the user-input string
        {
            while(str.indexOf(" ") > -1)
            {
                reversePhrase = str.substring(0, str.indexOf(" ")); //this might be the problem, but i'm stuck on any solutions
                str = str.substring(1 + str.indexOf(" "));
                reversePhrase = str + " "+ reversePhrase;
            }
            System.out.println(reversePhrase);  //only reverses and prints last two words in phrase
        }
        else if(!(str.indexOf(" ") > -1))   //if there's no space in the user-input string
        {
            for(position = str.length() - 1; position >= 0; position --)    //does this conflict with the "for" parameter above?
            {
                while(position >= 0)    //wasn't sure what to put for this parameter
                {
                    reverseLetter = str.charAt(position);
                    reverseWord = reverseLetter + reverseWord;
                }
            }
            System.out.println(reverseWord);
        }
    }
3 Answers

When writing code, always try to follow the KISS principle. Keep it simple stupid. You were lost in the nested for-if-while loops that make it hard to figure out where it goes wrong.

Another principle is: don't overload your methods with multiple tasks. Use small and simple methods that only do one task at a time. Below, for example, I've put reversePhrase and reverseWord into their own methods. That helps you to make a clean main method.

public static void main(String args[]) {
    Scanner userInput = new Scanner(System.in);
    System.out.print("Enter a word or phrase: ");
    String str = userInput.nextLine();

    //if input contains spaces call reversePhrase otherwise reverseWord
    //str.contains(" ") is IMO cleaner, but you can change it to str.indexOf(" ") > -1 if you find it better
    if(str.contains(" ")){
        System.out.println(reversePhrase(str));
    }
    else{
        System.out.println(reverseWord(str));
    }
}

private static String reverseWord(String input) {
    String result = "";
    for(int i = input.length()-1; i >= 0; i--){
        result = result + input.charAt(i);
    }
    return result;
}

private static String reversePhrase(String input) {
    String result = "";
    while(input.contains(" ")){
        result = result + input.substring(input.lastIndexOf(" ")+1) + " ";
        input = input.substring(0, input.lastIndexOf(" "));
    }
    return result + input;
}

In your while loop:

while(position >= 0){    //wasn't sure what to put for this parameter
     reverseLetter = str.charAt(position); // position stays the same
     reverseWord = reverseLetter + reverseWord;
}

It doesn't change the value of position. (position will never be 0) I would recommend adding position-- at the end, like so:

while(position >= 0){    //wasn't sure what to put for this parameter
     reverseLetter = str.charAt(position); // position stays the same
     reverseWord = reverseLetter + reverseWord;
     position--;
}

It would change the value of the position variable.

Also, you have one if and one else if in your code. I would recommend changing else if to else as it's pointless to do:

boolean randomBoolean = new java.util.Random().nextBoolean();
if(randomBoolean){...}
else if(!randomBoolean){...} // If randomBoolean == false, then this code will execute anyway

I've removed one of the for loops, because you don't need it. Also, the while loop for the case of one word. And for the first case, you can use another String to temporaly save the last word. Here's the result:

public static void main(String[] args) {
    Scanner userInput = new Scanner(System.in);

    System.out.print("Enter a word or phrase: ");
    String str = userInput.nextLine();  //user-input string

    String reversePhrase = "";  //placeholder for reversed phrase
    String reverseWord = "";    //placeholder for reversed word
    char reverseLetter;   //placeholder for letters in reversed word
    final String space = " ";

    if(str.contains(space)) {
        while(str.contains(space))
        {
            int i = str.lastIndexOf(space);
            String lastWord = str.substring(i);
            str = str.substring(0, i);
            reversePhrase += lastWord;
        }
        //We add the first word
        reversePhrase = reversePhrase + space + str;
        System.out.println(reversePhrase.trim());
    }
    else {
        for(int position = str.length() - 1; position >= 0; position --) {
            reverseLetter = str.charAt(position);
            reverseWord =  reverseWord + reverseLetter;
        }
        System.out.println(reverseWord);
    }
}
Related