Home  >  Article  >  Java  >  How to use java scanner

How to use java scanner

(*-*)浩
(*-*)浩Original
2019-05-21 16:43:4859318browse

java.util.Scanner is a new feature of Java5. We can obtain user input through the Scanner class.

How to use java scanner

The following is the basic syntax for creating a Scanner object:

Scanner s = new Scanner(System.in);

Next we demonstrate the simplest data input and pass next() of the Scanner class Use the nextLine() method to obtain the input string. Before reading, we generally need to use hasNext and hasNextLine to determine whether there is still input data:

Use the next method:

import java.util.Scanner; 
 
public class ScannerDemo {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);        // 从键盘接收数据
 
        // next方式接收字符串
        System.out.println("next方式接收:");        // 判断是否还有输入
        if (scan.hasNext()) {
            String str1 = scan.next();            
            System.out.println("输入的数据为:" + str1);        
         }
        scan.close();    
      }
}

The output result of executing the above program is:

next方式接收:
runoob com
输入的数据为:runoob

You can see that the com string is not output, let’s look at nextLine next.

Use nextLine method:

import java.util.Scanner;
 
public class ScannerDemo {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        // 从键盘接收数据
 
        // nextLine方式接收字符串
        System.out.println("nextLine方式接收:");
        // 判断是否还有输入
        if (scan.hasNextLine()) {
            String str2 = scan.nextLine();
            System.out.println("输入的数据为:" + str2);
        }
        scan.close();
    }
}

The output result of executing the above program is:

nextLine方式接收:
runoob com
输入的数据为:runoob com

You can see the com string output .

The difference between next() and nextLine()

next():

1. Be sure to read it to be valid characters before the input can be completed.

2. The next() method will automatically remove the blanks encountered before entering valid characters.

3. Only after entering valid characters, use the blank space entered after them as the separator or terminator.

next() cannot get a string with spaces.

nextLine():

1. Enter is the end character, which means that the nextLine() method returns all characters before entering.

2. Can get blank space.

The above is the detailed content of How to use java scanner. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn