For example I want to accept Hammer or Nail Gun with the space. I am sending this information as a string to a method, so I can not have a space after. I need to send either “Hammer” or “Nail Gun” and other similar items with one or two words only.
String name = console.next() + " " + console.next();
fails to work as if someone enters Hammer, it waits for the next entry.
Btw, I can use console.nextLine, but was hoping to add some security as to full line of code.
Assuming
consoleis an instance ofScanner, there are many ways to solve this problem.The simplest is to use
console.nextLine()instead of.next(). That way, the user can enter multiple words and complete their input by pressing Enter.Alternatively, you could use
console.nextLine(Pattern pattern)and provide a pattern which is a regular expression that matches your desired input.