This code is inside the main
function:
Scanner input = new Scanner(System.in);
System.out.println(\"Type a sentence\");
String sentence = input
I assume that what you want your code to do is to reverse each word in turn, not the entire string. So, given the input example sentence
you want it to output elpmaxe ecnetnes
not ecnetnes elpmaxe
.
The reason that you see lpmaxe
instead of elpmaxe
is because your inner while
-loop doesn't process the last character of the string since you have i < sentence.length() - 1
instead of i < sentence.length()
. The reason that you only see a single word is because your sentence
variable consists only of the first token of the input. This is what the method Scanner.next()
does; it reads the next (by default) space-delimited token.
If you want to input a whole sentence, wrap up System.in
as follows:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
and call reader.readLine()
.
Hope this helps.