Scanner is not reading the whole sentence. Or let\'s say I\'m writing a method which reverses the words in a sentence while keeping them in their order in a sentence.
You use scan.next()
. This reads until whitespace (or whatever delimiter you set earlier, which you haven't). The default delimiter is whitespace.
Use scan.nextLine()
to read an entire line of text (i.e. until you press enter).
From the documentation:
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. [...]
You can change the delimiter by using useDelimiter
public Scanner useDelimiter(Pattern pattern)
Sets this scanner's delimiting pattern to the specified pattern.
you need to use nextline() function instead of next() to capture the whole line
Change String s= scanner.nextLine();
instead of String s= scanner.next();