use scanner in Java

The scanner is a class in java.util package. This class is responsible for reading data from a string, the keyboard, a file, or a network socket. This article focuses solely on reading the keyboard input and displaying the output in a terminal window. Reading data from a file or a network channel is done similarly. The scanner does not print the terminal window. Use the System.out object to print to the terminal. It’s easy to print to the terminal with this object.

The Scanner class is first imported before it is used. Following that, an object is created from it. The Scanner object must be closed after it has been used. System.in is the input stream object that represents the keyboard. The scanner is used in a variety of ways. In this article, we will discuss the commonly used ones.

The Java Scanner class divides the input into tokens by default using whitespace as a delimiter. It has several methods for reading and parsing various primitive values. Also, the Java Scanner class frequently employs a regular expression to parse text for strings and primitive types. It is the most straightforward method of obtaining input in Java. Using Java’s Scanner, we may get input from the user in primitive types such as int, long, double, byte, float, short, and so on.

Methods of the Java Scanner Class

The procedures of the scanner are as follows:

close()

It’s used to shut down the scanner.

delimiter()

It’s used to acquire the Pattern that the Scanner class is using to match delimiters.

findAll()

It’s used to find a stream of match results that match the pattern string provided.

findInLine()

It’s used to discover the next occurrence of a pattern made up of the provided string without considering delimiters.

findWithinHorizon()

It’s used to discover the next occurrence of a pattern made up of the provided string without considering delimiters.

hasNext()

In case the given scanner has another token in its input, it returns true.

hasNextBigDecimal()

It’s used to determine whether or not the next token in this scanner’s input can be read as a BigDecimal using the nextBigDecimal() method.

hasNextBigInteger()

It determines whether or not the next token in this scanner’s input can be read as a BigDecimal using the nextBigDecimal() method.

hasNextBoolean()

It’s used to determine whether or not the next token in this scanner’s input may be translated as a Boolean using the nextBoolean() method.

hasNextByte()

It is used to determine whether or not the next token in this scanner’s input can be read as a Byte using the nextBigDecimal() method.

hasNextDouble()

It is used to determine whether or not the next token in this scanner’s input can be read as a BigDecimal using the nextByte() method.

hasNextFloat()

It is used to determine whether or not the next token in this scanner’s input may be read as a Float using the nextFloat() method.

hasNextInt()

It is used to determine whether or not the next token in this scanner’s input can be read as an int using the nextInt() method.

hasNextLine()

It’s used to see if there’s another line in the scanner’s input.

hasNextLong()

It is used to determine whether or not the next token in this scanner’s input is read as a Long using the nextLong() method.

hasNextShort()

It is used to determine whether or not the next token in this scanner’s input may be read as a Short using the nextShort() method.

ioException()

It’s used to retrieve the last IOException thrown by this scanner.

 

The Scanner Class is used straightforwardly. The following code prompts the user to input a sentence, which is subsequently displayed:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import java.util.Scanner;

public class CodeClass {

  public static void main(String[] args) {

      Scanner scanCode = new Scanner(System.in);
System.out.println("Start by typing  a sentence, then, press Enter:");

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

scanCode.close();
  }
}
</pre>
</div>

The Scanner class is imported in the first line. The first line of the main function creates a scanner object by referencing the “System.in” object for the keyboard. The scanner object begins waiting for input as soon as it is created. The next line prints a statement that prompts the user to input a sentence. The next line of code utilizes the scanner object’s nextLine() method to read the user’s sentence once he presses Enter.

The next line reprints the sentence in the terminal window in the code. The scanner object is closed with the last line.

Spitting Values from the Input Line

Using the space as a delimiter, the following code divides the input line into words (tokens):

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import java.util.Scanner;

public class CodeClass {
  public static void main(String[] args) {
      Scanner scanCode = new Scanner(System.in);
System.out.println(" Start by typing a line of tokens,then, press Enter:");

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

scanCode.close();
  }
}
</pre>
</div>

The scanner object contains two more methods: hasNext() and next(). When the scanner object reads a line, it is saved. next() gets you to the next token (word). If any additional tokens haven’t been accessed yet, hasNext() returns true.

Unfortunately, this method requires the user to key in input for splitting and re-displaying. To exit, hit Ctrl+z, and you’ll be taken back to the command prompt.

The delimiter in the above code separates tokens in the space. It’s possible to use a different character. The comma is used in the following code. If you’re testing the code, don’t forget to hit Ctrl+z to end the loop.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import java.util.Scanner;

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

System.out.println("Typing tokens in a line, then, press Enter:");

scanCode.useDelimiter(",");

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

scanCode.close();
  }
}</pre>
</div>

If you tested the code (output), you might have noticed that spaces in tokens have been incorporated as part of tokens if you tested the code (output). After the input line has been read, type scanObj.useDelimiter(“,”); this is what makes the comma the delimiter.

Primitive Data Types: Reading and Validation

nextBoolean() as a method returning a Boolean value

The user is expected to type “true” or “false” without the quotations in the following code and then press the Enter key. If the user types anything else, such as “yes” or “no,” an error notice will appear.

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import java.util.Scanner;

public class CodeClass {
  public static void main(String[] args) {

System.out.print("Kindly confirm if you are below 50? ");  
      Scanner scanCode = new Scanner(System.in);

boolean boolVal = scanCode.nextBoolean();  
      if (boolVal == true) {  
System.out.println("You are below 50");  
      }
      else if (boolVal == false) {  
System.out.println("You are over 50");  
      }

scanCode.close();  
  }
}</pre>
</div>

Because java will throw an error if the input isn’t exactly true or false, “else if” has been used instead of “else.” The distinction between print and println is that print expects input on the current line, whereas println expects input on the following line.

nextByte() as a method

A character in the ASCII character set is one byte. In some Eastern character sets, however, a character can be made up of more than one byte. The nextByte method reads and validates the next byte of the input regardless of the character set. For this, the following code is used:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import java.util.Scanner;

public class CodeClass {

  public static void main(String[] args) {

System.out.print("Enter a number below 300,then, press Enter: ");  
      Scanner scanCode = new Scanner(System.in);

      byte nextByte = scanCode.nextByte();  
System.out.println(nextByte);  

scanCode.close();  
  }
}</pre>
</div>

An error warning is displayed if a number greater than 300 or an alphabet character is entered for this code.

nextInt() as a method

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

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import java.util.Scanner;

public class CodeClass {

  public static void main(String[] args) {

System.out.print("Input any Integer Value: ");  
      Scanner scanCode = new Scanner(System.in);

      int numVar = scanCode.nextInt();  
System.out.println(numVar);  

scanCode.close();  
  }
}</pre>
</div>

There are no more leading or trailing spaces. Any integer value, including values more than 300, would be allowed for this code. An error message is displayed when the validation fails using these nextXXX() methods.

Method nextBigInteger()

It appears as if software engineers will never run out of new ideas. A big integer is a number with a value substantially larger than an integer. However, it is read the same way as an integer in Java. The following code demonstrates this:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import java.util.Scanner;
import java.math.BigInteger;

public class CodeClass {
  public static void main(String[] args) {

System.out.println("Input an Integer of your choice for Big Integer: ");  
      Scanner scanCode = new Scanner(System.in);

BigInteger numVar = scanCode.nextBigInteger();  
System.out.println(numVar);  

scanCode.close();  
  }
}</pre>
</div>

The import sentence “import java.math.BigInteger;” should be noted. Also, the big integer type is denoted by an uppercase B rather than a lowercase b.

nextFloat() as a method

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

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import java.util.Scanner;

public class CodeClass {

  public static void main(String[] args) {

System.out.print("Input any Float Value: ");  
      Scanner scanCode = new Scanner(System.in);

      float numVar = scanCode.nextFloat();
System.out.println(numVar);  

scanCode.close();  
  }
}</pre>
</div>

23.456 is an example of a float number. There are no more leading or trailing spaces.

nextDouble()

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

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import java.util.Scanner;

public class CodeClass {

  public static void main(String[] args) {

System.out.print("Input any Double Value: ");  

      Scanner scanCode = new Scanner(System.in);

      double numVar = scanCode.nextDouble();
System.out.println(numVar);  

scanCode.close();  
  }
}</pre>
</div>

23.456 is an example of a double number. A double number differs from a float because it has a smaller error margin. There are no more leading or trailing spaces.

nextLine() as a Method

The nextLine() method finds the next line in a string. The newline character, ‘\n,’ can be used if the string is the input line from the keyboard after hitting Enter. You can use the following code:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import java.util.Scanner;

public class CodeClass {
  public static void main(String[] args) {

System.out.println("Input a line showing  \\n : ");  

      Scanner scanCode = new Scanner(System.in);

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

scanCode.close();  
  }</pre>
</div>

It’s worth noting that the string type starts with an uppercase S rather than a lowercase s. In this article, the nextLine(), hasNext(), and next() methods were utilized earlier. Other ways and rudimentary data methods are available on the scanner – more on that later.

Assigning an Input to a specific Variable

As shown in the code below, the input can be assigned to a variable:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import java.util.Scanner;

public class CodeClass {

  public static void main(String[] args) {

      Scanner scanCode = new Scanner(System.in);

System.out.print("Enter Name: ");
      String nameVal = scanCode.nextLine();  

System.out.print("Input your age: ");
      int ageVal = scanCode.nextInt();  

System.out.print("Enter your current remuneration: ");
      double salaryVal = scanCode.nextDouble();  

System.out.println("Your name is: " + nameVal + ", and your age is: " + ageVal + ", While your current remuneration is: " + salaryVal);  

scanCode.close();  
  }
}</pre>
</div>

Example: Reading user input and displaying back to the user

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre> // initially, Import the Scanner class as follows
import java.util.Scanner;

class CodeMain {

  public static void main(String[] args) {

    Scanner scanCode = new Scanner(System.in);  // Creation of a Scanner object
    System.out.println("Input your username");

    String codeUserName = scanCode.nextLine();  // Reading the user input
    System.out.println(" Your Username is: " + codeUserName);  // Output the user input
  }
}</pre>
</div>

Example: Using different methods for reading data of various types

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>import java.util.Scanner;

class CodeMain {

  public static void main(String[] args) {

    Scanner scanCode = new Scanner(System.in);

    System.out.println("Please provide your name, your current age, and your current remuneration:");

    // String input
    String enterYourName = scanCode.nextLine();

    // Numerical input
    int enterYourAge = scanCode.nextInt();
    double enterYourSalary = scanCode.nextDouble();

    // Output user's input
    System.out.println("Your name is: " + enterYourName);
    System.out.println("Your age is: " + enterYourAge);
    System.out.println("Your salary is: " + enterYourSalary);
  }
}</pre>
</div>

Conclusion

The scanner is a class in java.util package. This class is responsible for reading data from a string, the keyboard, a file, or a network socket. This essay focuses on reading the keyboard input and showing the output in the terminal window. Reading input from a string, file, or network channel can be done similarly.

Use the nextLine() function to read the entire line of keyboard input. The hasNext(), next() methods, and the while loop are used to split a line into tokens. Further, the space is the default split delimiter, although the programmer can use any other delimiter. Remember to press Ctrl+z to exit the while loop if necessary.

Other systems not covered in this article are used to remove leading and trailing spaces. Additionally, other schemes not present here can be used to validate the tokens. NextBoolean(), nextByte(), nextInt(), and other primitive functions can be used to read primitive values. These nextXXX() methods check for errors and eliminate leading and trailing spaces.

There are many more methods in the Java Scanner. However, the scanner’s basic operation has been covered in this article. Thus the selection of a token is accomplished through the use of regular expressions.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *