Hi, I've recently started learning java in college. Hoping someone can throw me a bone.
I was give an assignment to make a method to reverse a sentence.
I can only use loops, if statements and other methods(no arrays).
For example "Hello there how are you" would be output as "you are how there Hello"
I've gotten 90% of it working, but it keeps excluding the first word i enter.
So the output that keeps appearing is "you are how there" (the "hello" is missing).
//start backwards method
public static String backwards(String theString)
{
String newString = "";
int i = 0;
int space = 0;
int lastSpace = theString.length()-1;
theString = theString.trim();
for (i = theString.length() - 1; i >= 0; i--)//starting at the end of string
{
if (theString.charAt(i) == ' ')
{
space = i;
newString = newString + theString.substring(space,lastSpace);
lastSpace = i;
}
}
return newString;
} //end backwards method
Like I said this almost works, except for the very first word entered.
Any ideas? then thanks in advance! =)