Java

How to use Scanner in Java

The Scanner in Java is a class in java.util package. This class aims to read input from a string, the keyboard, file, or network socket. This article concentrates only on reading input from the keyboard and displaying the result at the terminal window. Similar ideas can be used to read input from the file or network channel. The Scanner does not print to the terminal window. To print to the terminal, use the System.out object. It is simple to use this object to print to the terminal, as illustrated below.

To use the Scanner class, it has to be imported first. After that, an object has to be instantiated from it. After using the Scanner object, it has to be closed. The input stream object that represents the keyboard is System.in. The scanner has many methods. Only the commonly used ones will be explained in this article.

Article Content

Simple use of the Scanner Class

The following code asks the user to type in a sentence, and then it displays the sentence:

import java.util.Scanner;

public class TheClass {
  public static void main(String[] args) {
      Scanner scanObj = new Scanner(System.in);
System.out.println("Type a sentence and press Enter:");

      String sentence = scanObj.nextLine();
System.out.println(sentence);

scanObj.close();
  }
}

The first line imports the Scanner class. In the main function, the first line creates a scanner object using the “System.in” object for the keyboard. As soon as the scanner object is created, it starts waiting for input. The next line prints a statement, asking the user to type in a sentence. The line following in the code uses the nextLine() method of the scanner object to read the user’s sentence after he presses Enter. The line after, in the code, reprints the sentence at the terminal window. The last line closes the scanner object.

Spitting Input Line into Values

The following code splits the input line into words (tokens), using the space as delimiter:

import java.util.Scanner;

public class TheClass {
  public static void main(String[] args) {
      Scanner scanObj = new Scanner(System.in);
System.out.println("Type a line of tokens, and press Enter:");

while(scanObj.hasNext()){  
System.out.println(scanObj.next());  
      }

scanObj.close();
  }
}

hasNext() and next() are two other methods of the scanner object. When the scanner object reads a line, it keeps it. next() accesses the next token (word). hasNext() returns true if there is any other token not yet accessed.

Unfortunately, the user is still expected to type in input for splitting and re-displaying with this code. To end all that, press Ctrl+z, and you should be back at the command prompt.

In the above code, the delimiter separates tokens in the space. Another character can be used. The following code uses the comma. Do not forget to press Ctrl+z to end the loop if you test the code.

import java.util.Scanner;

public class TheClass {
  public static void main(String[] args) {
      Scanner scanObj = new Scanner(System.in);
System.out.println("Type a line of tokens, and press Enter:");

scanObj.useDelimiter(",");

while(scanObj.hasNext()){  
System.out.println(scanObj.next());  
      }

scanObj.close();
  }
}

If you tested the code, you would have noticed that spaces in tokens have been included as part of tokens (output). The expression, scanObj.useDelimiter(“,”); typed after the input line has been read; it is what makes comma, the delimiter.

Reading and Validating Primitive Data Types

nextBoolean() method

In the following code, the user is expected to type either “true” or “false” without the quotes and then press the Enter key if the user types anything else, such as “yes” or “no”, an error message will be displayed.

import java.util.Scanner;

public class TheClass {
  public static void main(String[] args) {
System.out.print("Are you above 24? ");  
      Scanner scanObj = new Scanner(System.in);

boolean bl = scanObj.nextBoolean();  
      if (bl == true) {  
System.out.println("You are over 24");  
      }
      else if (bl == false) {  
System.out.println("You are under 24");  
      }

scanObj.close();  
  }
}

Since java will issue an error message as long as the input is not true or false exactly, the “else if” has been used instead of “else”.

The difference between the methods, print and println, is that print expects the input on the current line, while println expects the input on the next line.

nextByte() method

With the ASCII character set, a character is one byte. However, with some Eastern character sets, a character may consist of more than one byte. Independent of the character set, the nextByte method reads and validates the next byte of the input. The following code can be used for this purpose:

import java.util.Scanner;

public class TheClass {
  public static void main(String[] args) {
System.out.print("Type number < 128, press Enter: ");  
      Scanner scanObj = new Scanner(System.in);

      byte bt = scanObj.nextByte();  
System.out.println(bt);  

scanObj.close();  
  }
}

If a number greater than 127 or an alphabet character is inputted for this code, an error message would be issued.

nextInt() Method

The next integer token as an input can also be validated and accepted. The following code can be used:

import java.util.Scanner;

public class TheClass {
  public static void main(String[] args) {
System.out.print("Enter any Integer: ");  
      Scanner scanObj = new Scanner(System.in);

      int num = scanObj.nextInt();  
System.out.println(num);  

scanObj.close();  
  }
}

Leading or trailing spaces have been removed. For this code, any integer value, including values greater than 127, would be accepted. With these nextXXX() methods, once the validation fails, an error message is issued.

nextBigInteger() Method

It seems software engineers will never stop coming up with new things. A big integer is an integer whose value is much bigger than that of an integer. However, with Java, it can be read in the same way as the integer. The following code illustrates this:

import java.util.Scanner;
import java.math.BigInteger;

public class TheClass {
  public static void main(String[] args) {
System.out.println("Enter any Integer for Big Integer: ");  
      Scanner scanObj = new Scanner(System.in);

BigInteger num = scanObj.nextBigInteger();  
System.out.println(num);  

scanObj.close();  
  }
}

Note the import statement, “import java.math.BigInteger;”. Also, note that the big integer type is begun with an uppercase B and not a lowercase b.

nextFloat() Method

The next float token as an input can also be validated and accepted. The following code can be used:

import java.util.Scanner;

public class TheClass {
  public static void main(String[] args) {
System.out.print("Enter any Float: ");  
      Scanner scanObj = new Scanner(System.in);

      float num = scanObj.nextFloat();
System.out.println(num);  

scanObj.close();  
  }
}

An example of a float number is 23.456. Leading or trailing spaces have been removed.

nextDouble()

The next double token as an input can also be validated and accepted. The following code can be used:

import java.util.Scanner;

public class TheClass {
  public static void main(String[] args) {
System.out.print("Enter any Double: ");  
      Scanner scanObj = new Scanner(System.in);

      double num = scanObj.nextDouble();
System.out.println(num);  

scanObj.close();  
  }
}

An example of a double number is 23.456. A double number is different from a float because it has less margin of error. Leading or trailing spaces have been removed.

nextLine() method

The nextLine() method is for a string. If the string is the input line from the keyboard after pressing Enter, it can have the newline character, ‘\n’. The following code can be used:

import java.util.Scanner;

public class TheClass {
  public static void main(String[] args) {
System.out.println("Enter a line having \\n : ");  
      Scanner scanObj = new Scanner(System.in);

      String str = scanObj.nextLine();
System.out.println(str);  

scanObj.close();  
  }
}

Notice that the string type is begun with the uppercase S and not the lowercase s.

The nextLine(), hasNext() and next() methods have been used previously, in this article. The scanner has other methods and other primitive data methods – see later.

Assigning Input to a Variable

Input can be assigned to a variable, as the following code shows:

import java.util.Scanner;

public class TheClass {
  public static void main(String[] args) {
      Scanner scanObj = new Scanner(System.in);

System.out.print("Enter Name: ");
      String name = scanObj.nextLine();  

System.out.print("Enter Age: ");
      int age = scanObj.nextInt();  

System.out.print("Enter Salary: ");
      double salary = scanObj.nextDouble();  

System.out.println("Name: " + name + ", Age: " + age + ", Salary: " + salary);  

scanObj.close();  
  }
}

Conclusion

The Scanner in Java is a class in java.util package. This class aims to read input from a string, the keyboard, file, or network socket. This article has concentrated mainly on reading input from the keyboard and displaying the result at the terminal window. Similar ideas can be used to read input from the string, file, or network channel.

To read the entire line of keyboard input, use the nextLine() method. The line as a string can be split into tokens, using the hasNext() and next() methods, and the while loop. The default delimiter for splitting is the space, but the programmer can choose some other delimiter. Do not forget to do Ctrl+z to stop the while loop, if necessary. Removing leading and trailing spaces can be done using other schemes not addressed in this article. Validation of the tokens can also be done using other schemes not addressed in this article.

Primitive values can be read using nextBoolean(), nextByte(), nextInt(), etc. These nextXXX() methods do validation, and also remove leading and trailing spaces.

The Java Scanner has many more methods. However, the basic use of the Scanner has been explained in this article. The selection of a token is actually done using regular expression techniques. The use of regular expression techniques is discussion, for some other time.

About the author

Chrysanthus Forcha

Discoverer of mathematics Integration from First Principles and related series. Master’s Degree in Technical Education, specializing in Electronics and Computer Software. BSc Electronics. I also have knowledge and experience at the Master’s level in Computing and Telecommunications. Out of 20,000 writers, I was the 37th best writer at devarticles.com. I have been working in these fields for more than 10 years.