Reversing characters in each word in a sentence - Stack Implementation

前端 未结 6 1422
情深已故
情深已故 2020-12-22 06:02

This code is inside the main function:

Scanner input = new Scanner(System.in);

System.out.println(\"Type a sentence\");
String sentence = input         


        
6条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-22 06:36

    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.

提交回复
热议问题