What’s the difference between next() and nextLine() methods from Scanner class?

I always prefer to read input using nextLine() and then parse the string. Using next() will only return what comes before the delimiter (defaults to whitespace). nextLine() automatically moves the scanner down after returning the current line. A useful tool for parsing data from nextLine() would be str.split(“\\s+”). For more information regarding the Scanner class or String class refer to the following links. Scanner: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html … Read more

What does Scanner input = new Scanner(System.in) actually mean?

Alright, let’s elaborate with some simplified explanation about the Scanner class. It is a standard Oracle class which you can use by calling the import java.util.Scanner. So let’s make a basic example of the class: Now when you call Scanner input = new Scanner(System.in); you make a new object of the Scanner class (so you make a new “Scanner”) and you store … Read more

Validating input using java.util.Scanner

Overview of Scanner.hasNextXXX methods java.util.Scanner has many hasNextXXX methods that can be used to validate input. Here’s a brief overview of all of them: hasNext() – does it have any token at all? hasNextLine() – does it have another line of input? For Java primitives hasNextInt() – does it have a token that can be parsed into an int? Also available are hasNextDouble(), hasNextFloat(), hasNextByte(), hasNextShort(), hasNextLong(), and hasNextBoolean() As bonus, there’s … Read more

Rock, Paper, Scissors Game Java

I would recommend making Rock, Paper and Scissors objects. The objects would have the logic of both translating to/from Strings and also “knowing” what beats what. The Java enum is perfect for this. The parseType method can return null if the String is not a valid type. And you code can check if the value is null and if … Read more

Exception in thread “main” java.util.NoSuchElementException

You close the second Scanner which closes the underlying InputStream, therefore the first Scanner can no longer read from the same InputStream and a NoSuchElementException results. The solution: For console apps, use a single Scanner to read from System.in. Aside: As stated already, be aware that Scanner#nextInt does not consume newline characters. Ensure that these are consumed before attempting to call nextLine again by using Scanner#newLine(). See: Do not create multiple buffered wrappers on … Read more