Two problems:
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.
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);
}
}