Java Basics - Scanner Class

1 Overview

(1) ScannerClass is a tool class in Java for reading user input . It can read data from a variety of input sources , such as standard input, files, or strings. The Scanner class provides a series of methods to handle input of different data types, such as integers, floating point numbers, Boolean values, characters, and strings.

(2) There are two important methods in the Scanner class:

  • Methods starting with hasNext: used to check whether the next tag is available in the input source, commonly used are:
    • hasNext(): Returns true if there is a next token (non-space character) left in the input source.
    • hasNextLine(): Returns true if there is a next line (non-empty line) in the input source.
    • hasNextInt(): Returns true if there is the next integer in the input source.
    • hasNextDouble(): Returns true if there is another float in the input source.
    • hasNextBoolean(): Returns true if there is a next boolean value in the input source.
  • Methods starting with next: used to get the next tag from the input source and return the corresponding data type, commonly used are:
    • next(): Obtain and return a string from the input source. By default, a space is used as the separator, and Enter is used as the end character. The content after the Enter is put into the buffer.
    • nextLine(): Fetches and returns a line of strings (delimited by newlines) from the input source.
    • nextInt(): Get and return an integer from the input source.
    • nextDouble(): Get and return a floating point number from the input source.
    • nextBoolean(): Takes and returns a boolean value ("true" or "false") from the input source.

(3) next()and nextLine()There are some differences in processing methods and usage scenarios:

  • next()method:
    • The string read does not contain delimiters, if there are more than one space-separated words in the input, next()the method will only return the first word .
    • Leading whitespace in the input is ignored before reading .
  • nextLine()method:
    • Reads and returns a full line of string from the input source, including newlines \n.
    • It reads the entire content of the input source until a newline character is encountered, or the input ends.
    • nextLine()The string returned by the method can contain spaces and other special characters.

2. Example of use

2.1. Reading data from different input sources

When using the Scanner class, data can be read from various input sources, including standard input, files, and strings. Here are a few examples using different input sources:

(1) Read data from the standard input stream

public class Example {
    
    
    public static void main(String[] args) {
    
    
        // 创建 Scanner 对象,使用标准输入流作为输入源
        Scanner scanner = new Scanner(System.in);

        System.out.print("请输入一个整数:");
        int number = scanner.nextInt(); // 从标准输入流读取整数

        System.out.println("你输入的整数是:" + number);

        scanner.close();
    }
}

In this example, we create a Scanner object with the standard input stream (System.in) as the input source. Then we use nextInt()the method to read an integer from the standard input stream.

(2) Read data from the file

public class Example {
    
    
    public static void main(String[] args) {
    
    
        try {
    
    
            // 创建 Scanner 对象,使用文件作为输入源
            Scanner scanner = new Scanner(new File("input.txt"));

            while (scanner.hasNextLine()) {
    
    
                String line = scanner.nextLine(); // 从文件读取一行数据
                System.out.println(line);
            }

            scanner.close();
        } catch (FileNotFoundException e) {
    
    
            e.printStackTrace();
        }
    }
}

In this example, we create a Scanner object with the file "input.txt" as the input source. Then we use the hasNextLine()and nextLine()method to loop through each line of data in the file and print it out.

(3) Read data from string

public class Example {
    
    
    public static void main(String[] args) {
    
    
        String input = "Hello World 123";
        // 创建 Scanner 对象,使用字符串作为输入源
        Scanner scanner = new Scanner(input);
        while (scanner.hasNext()) {
    
    
            if (scanner.hasNextInt()) {
    
    
                int number = scanner.nextInt(); // 从字符串读取整数
                System.out.println("整数:" + number);
            } else {
    
    
                String word = scanner.next(); // 从字符串读取单词
                System.out.println("单词:" + word);
            }
        }
        scanner.close();
    }
}

In this example, we create a Scanner object with the string "Hello World 123" as the input source. Then we use the hasNext(), hasNextInt()and next()methods to loop through each word or integer in the string and print it out.

2.2. The difference between next() and nextLine()

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

        // next() && nextLine()
        System.out.println("请输入一个字符串 nextLine():");
        String str1 = scanner.nextLine();
        System.out.println(str1);

        System.out.println("请输入一个字符串 next():");
        String str2 = scanner.next();
        System.out.println(str2);
    }
}

The result is as follows:

请输入一个字符串 nextLine():
   Hello World  
nextLine() 的读取结果为: 
   Hello World  

请输入一个字符串 next():
   Hello   World
next() 的读取结果为: 
Hello

2.3. Read a one-dimensional array of known size

Description: The input in the first line is an integer n, representing the length of the array nums, the input in the second line is n integers, and the integers are separated by spaces. Please store these integers in the array nums and print it out. For example:

7
4 9 0 -1 6 8 9

(1) Use to nextInt()read one by one:

class Solution {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        //数组的长度
        int n = scanner.nextInt();
        int[] nums = new int[n];
        //数组中的 n 个数
        for (int i = 0; i < n; i++) {
    
    
            nums[i] = scanner.nextInt();
        }
        System.out.println("数组 nums 的元素为:");
        for (int num : nums) {
    
    
            System.out.print(num + " ");
        }
        scanner.close();
    }
}

The result is as follows:

7
4 9 0 -1 6 8 9
数组 nums 的元素为:
4 9 0 -1 6 8 9 

(2) Use nextLine()to read all of them first, and then interpret them one by one:

class Solution {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        //清除缓冲区中的换行符
        scanner.nextLine();
        int[] nums = new int[n];
        String input = scanner.nextLine();
        //以一个或者多个空格为分隔符
        String[] numStrings = input.split("\\s+");
        for (int i = 0; i < n; i++) {
    
    
            nums[i] = Integer.parseInt(numStrings[i]);
        }
        System.out.println("数组 nums 的元素为:");
        for (int num : nums) {
    
    
            System.out.print(num + " ");
        }
        scanner.close();
    }
}

Precautions:

  • Note that nextInt()after reading an integer using the method, the buffer will still contain a newline \n. This is because nextInt()only the integer part is read, not the newline character. When the method is called next nextLine(), it reads the remainder of the buffer, the portion containing only the newline characters. Therefore, in order to ensure that nextLine()the method can read the entire line of string entered by the user, we need to nextLine()clear the newline character in the buffer before calling the method.
  • By calling scanner.nextLine()but not storing its result in a variable, we are actually saying that we just want to read from the buffer and discard the newline. This way, the next nextLine()time the method is called, it will read the contents of the line entered by the user and save it to the string inputwithout being disturbed by previous line breaks. It is common practice to ensure that newlines in the buffer are cleared to avoid situations where incorrect input or skipped input occurs due to lingering newlines.
  • scanner.nextLine()If there is no such line of statement in the above code , the following error will occur:
7
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:592)
	at java.lang.Integer.parseInt(Integer.java:615)
	at Solution.main(Solution.java:15)

2.4. Read a one-dimensional array of unknown size

Description: Enter several integers, separated by spaces. Please store these integers in the array nums and print it out. For example:

1 12 3 4 5 6 

(1) Use to nextInt()read one by one:

class Solution {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        List<Integer> nums = new ArrayList<>();
        while (scanner.hasNextInt()) {
    
    
            nums.add(scanner.nextInt());
        }
        System.out.println("数组 nums 的元素为:");
        for (int num : nums) {
    
    
            System.out.print(num + " ");
        }
        scanner.close();
    }
}

Precautions:

  • If you manually input several integers on the console and expect the program to end reading the integers after manually stopping the input, you can use other methods to indicate the conditions for ending the input. A common way is to indicate the end by entering a specific character or string;
  • Since it is read one by one, the length of the array is not known in advance, so the above code uses list to store;

(2) Use nextLine()to read all of them first, and then interpret them one by one:

class Solution {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        input = input.trim();
        String[] numStrings = input.split("\\s+");
        int[] nums = new int[numStrings.length];
        for (int i = 0; i < numStrings.length; i++) {
    
    
            nums[i] = Integer.parseInt(numStrings[i]);
        }
        System.out.println("数组 nums 的元素为:");
        for (int num : nums) {
    
    
            System.out.print(num + " ");
        }
        scanner.close();
    }
}

The result is as follows:

1 12 3 4 5 6 
数组 nums 的元素为:
1 12 3 4 5 6 

2.5. Read two-dimensional array with known length

Description: The first line of input is an integer m, indicating the length of the two-dimensional array nums, followed by m lines, each line has n integers, and the integers are separated by spaces. For example:

3
1 8 7 3
2 3 4 5
4 5 6 7
class Solution {
    
    
    public static void main(String[] args) {
    
    
        Scanner scanner = new Scanner(System.in);
        // 读取整数 m 作为二维数组的长度
        int m = scanner.nextInt();
        scanner.nextLine(); // 读取换行符
        //创建二维数组 nums
        int[][] nums = new int[m][];
        //读取m行数据到二维数组 nums
        for (int i = 0; i < m; i++) {
    
    
            //读取整行数据
            String line = scanner.nextLine();
            //将每个整数分割保存到一维数组
            String[] values = line.split("\\s+");
            //创建长度为 n 的一维数组
            int n = values.length;
            nums[i] = new int[n];
            //保存每个整数到一维数组
            for (int j = 0; j < n; j++) {
    
    
                nums[i][j] = Integer.parseInt(values[j]);
            }
        }
        //打印二维数组 nums
        System.out.println("数组 nums 的元素为:");
        for (int i = 0; i < m; i++) {
    
    
            for (int j = 0; j < nums[i].length; j++) {
    
    
                System.out.print(nums[i][j] + " ");
            }
            System.out.println();
        }
    }
}

The result is as follows:

3
1 8 7 3
2 3 4 5
4 5 6 7
数组 nums 的元素为:
1 8 7 3 
2 3 4 5 
4 5 6 7 

2.6. Read a two-dimensional jagged array of unknown length

Description: Enter several lines, each line has several integers, the integers are separated by spaces, and the integers in each line are not necessarily the same. For example:

1 2 3 45 
3 4 
9 0 -1 2 
1 4 6 
4 6 7 8 7 
class Solution {
    
    
    public static void main(String[] args) {
    
    
    	//也可选择使用字符串作为输入,方便测试
        String input = "1 2 3 45\n" +
                "3 4\n" +
                "9 0 -1 2\n" +
                "1 4 6\n" +
                "4 6 7 8 7";
                
        Scanner scanner = new Scanner(System.in);
        List<List<Integer>> nums = new ArrayList<>();
        // 逐行读取数据并保存到二维数组锯齿 nums
        while (scanner.hasNextLine()) {
    
    
            String line = scanner.nextLine();
            if (line.isEmpty()) {
    
    
                break; // 输入结束
            }
            String[] values = line.split("\\s+");
            List<Integer> row = new ArrayList<>();
            for (String value : values) {
    
    
                row.add(Integer.parseInt(value));
            }
            nums.add(row);
        }
        //打印二维锯齿数组 nums
        for (List<Integer> row : nums) {
    
    
            for (Integer value : row) {
    
    
                System.out.print(value + " ");
            }
            System.out.println();
        }
    }
}

The result is as follows:

1 2 3 45
3 4
9 0 -1 2
1 4 6
4 6 7 8 7

数组 nums 的元素为:
1 2 3 45 
3 4 
9 0 -1 2 
1 4 6 
4 6 7 8 7 

Guess you like

Origin blog.csdn.net/weixin_43004044/article/details/131867601