Java Scanner object

Java Scanner object


  • Java provides us with such a tool class that allows us to obtain user input. java.util.Scanner is a new journey of Java5, we can get user input through the Scanner class

  • Basic syntax:

    Scanner s = new Scanner(System.in);
    
  • The input string is obtained through the next() and nextLine() methods of the Scanner class. Before reading, we generally need to use hasNext() and hasNextLine() to determine whether there is any input data.


    • next():
    1. Be sure to read valid characters before you can end the input.
    2. If a blank is encountered before entering a valid character, the next() method will automatically remove it
    3. Only after valid characters are entered, the blank entered after it can be used as a separator or end character.
    4. next() cannot get a string with spaces.

    next() gets the input string and uses hasNext() to determine whether there is any input data

     		// 创建一个扫描器对象,用于接收键盘数据
            Scanner scanner = new Scanner(System.in);
            System.out.println("使用next方式接收:");
    
            // 判断用户有没有输入字符串
            if (scanner.hasNext()) {
          
          
                // 使用next方式接收
                String str = scanner.next();  // 程序会等待程序输入完毕
                System.out.println("输出内容为:"+str);
            }
            // 凡是属于IO流的类如果不关闭就会一直占用资源,要养成良好习惯用完就关掉
            scanner.close();
    

    • nextLine():
      1. Enter is the end character, that is to say, the nextLine() method returns all characters before the carriage return.
      2. can get blank

    nextLine() gets the input string Use hasNextLine() to determine whether there is any input data

    		// 创建一个扫描器对象,用于接收键盘数据
            Scanner scanner = new Scanner(System.in);
            System.out.println("使用nextLine方式接收:");
    
            // 判断用户有没有输入字符串
            if (scanner.hasNextLine()) {
          
          
                // 使用nextLine方式接收
                String str = scanner.nextLine();  // 程序会等待程序输入完毕
                System.out.println("输出内容为:" + str);
            }
            // 凡是属于IO流的类如果不关闭就会一直占用资源,要养成良好习惯用完就关掉
            scanner.close();
    

Guess you like

Origin blog.csdn.net/QTsong/article/details/123406677