Summary of Usage of Scanner in Java

  • 2021-12-05 06:03:59
  • OfStack

Recently, when doing OJ problems, the program often fails due to some detailed problems caused by the use of Scanner (the worst thing is Netease written test, because sc is dead loop and not found, resulting in AC code also fails...) Therefore, Scanner is summarized.

Brief introduction of Scanner class

Java 5 adds the java. util. Scanner class, a new utility for scanning input text.

It is some kind of combination between the previous StringTokenizer and Matcher classes. Because any data must be retrieved through the same 1 schema capture group or through the use of 1 index to retrieve various parts of the text.

You can then combine regular expressions with methods to retrieve specific types of data items from the input stream. This allows the Scanner class to parse strings and data of primitive types, such as int and double, arbitrarily, in addition to using regular expressions.

With Scanner, you can write a custom parser for any text content you want to process.

Understanding of nextInt (), next (), and nextLine ()

nextInt (): it only reads the int value, nextInt () places the cursor (cursor) in the same line after reading the input. (nextInt () only reads values, leaving "\ n" not read yet, and puts cursor in this line)

next (): read the input only till the space. It can 't read space space by space space space Also next () places the reading reading line reading reading reading reading reading reading reading

When the next () method meets the first valid character (non-space, non-line break), it starts scanning, and when it meets the first separator or terminator (space or line break), it ends scanning and obtains the scanned content, that is, it obtains the first scanned single string without space and line break.

nextLine(): reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.

nextLine (), you can scan 1 line of content and get it as a string.


public class NextTest{  
    public static void main(String[] args) {  
        String s1,s2;  
        Scanner sc=new Scanner(System.in);  
        System.out.print(" Please enter the 1 String: ");  
        s1=sc.nextLine();  
        System.out.print(" Please enter the 2 String: ");  
        s2=sc.next();  
        System.out.println(" The string entered is: "+s1+" "+s2);  
    }  
}  

Results:

Please enter the first string: home
Please enter the second string: work
The string entered is: home work

Modify the above program by 1:


s1=sc.next();  
s2=sc.nextLine();  

Run results:

Please enter the first string: home
Please enter the second string: The string entered is: home

As you can see, nextLine () automatically reads Enter removed by next () as its terminator, so there is no way to enter a value for s2 from the keyboard.

After verification, I found that other next methods, such as double nextDouble (), float nextFloat (), int nextInt (), etc., all have this problem when used with nextLine (). The solution is to add an nextLine () statement after every next (), nextDouble (), nextFloat (), nextInt (), etc., and filter out Enter terminators removed by next ().


public class NextTest{  
    public static void main(String[] args) {  
        String s1,s2;  
        Scanner sc=new Scanner(System.in);  
        System.out.print(" Please enter the 1 String: ");  
        s1=sc.next();  
        sc.nextLine();
        System.out.print(" Please enter the 2 String: ");  
        s2=sc.nextLine();  
        System.out.println(" The string entered is: "+s1+" "+s2);  
    }  
}  

Run results:

Please enter the first string: home
Please enter the second string: work
The string entered is: home work

Cyclic input of multiple sets of test cases

An while is a test case


    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        // 1 A while Is 1 Test cases 
        while(in.hasNext()){
            int n = in.nextInt(); //  Number of subsequent parameters received for this test case 
            long[] array = new long[n];
            String[] arrayStr = new String[n];
            for(int i=0; i<n; i++){
                arrayStr[i] = in.next();
            }
            for(int i=0; i<n; i++){
                array[i] = in.nextLong();//  Remove 1 Elements are converted to long Type 
            }
            System.out.println(Arrays.toString(array)+" "+ Arrays.toString(arrayStr));
        }
    }

A comprehensive example of combining with containers:


import java.util.Scanner;    
public class Main {    
    public static void main(String[] args) {    
        Scanner in = new Scanner(System.in);    
        while (in.hasNext()) {    
            int n = in.nextInt();   
        /* nextLine() It is the scanner that executes the current line and returns the skipped input information, which needs special attention! ! !  
 
             If there is no row, the 1 A in.nextLine() Command, the return value is int n = in.nextInt() Value of */   
            in.nextLine();  
        HashSet<String> set = new HashSet<String>();  
        for (int i = 0; i < n; i++) {   
        String line =   
  
        in.nextLine();   
        String[] arr = line.split(" ");   
        for (int j = 0; j < arr.length; j++) {   
            set.add(arr[j]);   
        }  
         }  
        System.out.println("sum:" + set.size()); 
    }    
}  

Enter:
3
a b c
d e f
a b c
Output:
6


Related articles: