Java scanner example – How to read data from console in java

The Java scanner example shows you how to read data from console in java and introduces the range of functionality of java.util.Scanner class. Java scanner can parse primitive types and strings using regular expressions. With a simple text, scanner breaks it into tokens using delimiter pattern, default token matches whitespace.

Here is first Java scanner example which use default token whitespace.

One more java scanner example that can also use delimiters other than whitespace. It reads several items in from a string:
String input = “1 dog or 2 dogs better”;
Scanner s = new Scanner(input).useDelimiter(“\s*dog\s*”);
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();

Other java scanner example which allows us to read a number from System.in:

You can use the next methods to read data. The method you use depends on the type of data you need to read. To read string data, for example, you use the next method. To read integer data, you use the nextInt method. To read byte data, you use the nextByte method. To read double data, you use the nextDouble method. And to read all of the data on a line, you use the nextLine method. And and many other methods you can use

Full Java Scanner example
In this example, let us together find out how to read data from console in java. When the program step over a method of the Scanner class, the application waits for the user to enter data with the keyboard. To complete the entry, the user presses the Enter key.

Let’s dig deeper
public Scanner(InputStream source) – Constructs a new Scanner that produces values scanned from the specified input stream. Bytes from the stream are converted into characters using the underlying platform’s default charset.

public String next() – Finds and returns the next complete token from this scanner.

public double nextDouble() – Scans the next token of the input as a double.

public int nextInt() – Scans the next token of the input as an int.

Run the above code then enter data and complete entry, we will get the results like below screen shoot:

Java scanner example - How to read data from console in java

That’s all on the Java Scanner example post. And hope that now you can get how to read data from console in java.

Leave a Comment

*

Please share it if you found this useful
Hide Buttons