Adam Chalkley wrote:. . . Mike Smith the first part of the string in this case Mark is cut off and only Smith . . .
Mark my words: don't create Scanner objects in your class. Create a utility class which has one Scanner field and use that scanner exclusively.
Features of utility classes:-
1: They only exist to help other code.2: They only have static members.2½: There is no need ever to create an instance of a static class.You can find out how to prevent instantiation from the
Java® Language Specification.
This thread shows how I would write a method to read the next
int. Never close that Scanner. The only problem with that version is that it isn't thread‑safe. Note how Stephan and I have taken completely different approaches to Scanners.
Are you using
next() or
nextLine()? If you use
next() with the default delimiter, you will get the first name, Malc, but it stops there. The second half Smith waits to be read later. If you use
nextLine() on its own without anything preceding, you would get Martin Smith as one String object. Note that you only ever get
null from a Scanner if you use one of the two methods whose name starts
find... All other methods return something, and if they have any difficulty finding what you are looking for, throw some sort of Exception.
Tell us what your book says
nextLine() does, then compare that to what the documentation does. That means that after
nextSomethingElse() [enter key], you may be right at the end of the line, so
nextLine() returns the empty String "", which is not equal to
null. If on the other hand, you are part‑way through a line, you will only get the second part of the line; it is clearly stated in the API documentation.
This is how I sorted that problem out:-
That will still only give you the right half of a line if you call it when half‑way along a line.
Once you get such a utility class working, you can enhance it and keep using it for ever.