The first stage: JAVA Quick Start (Fourth Lesson 25: Scanne method computers started obedient)

java.util.Scanner Java5 new features, we can get the user's input through the Scanner class.

Here is the basic syntax to create a Scanner object:

Scanner s = new Scanner(System.in);

Next, we demonstrate a simple data entry, and acquires the character string input through the next Scanner class () and nextLine () method, before reading the data we typically requires the use hasNext and determines whether there is input hasNextLine:

Use the next method:

ScannerDemo.java file code:

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 implementation of the above program output is:

next receiving mode: data is input runoob com: runoob

Com can see the output string does not, then we see nextLine.

Use nextLine method:

ScannerDemo.java file code:

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 implementation of the above program output is:

Com can see the output string.

next () and nextLine () difference

next():

  • 1, be sure to read to the end before they can enter a valid character.
  • 2, blank faced before entering a valid character, next () method will be automatically removed.
  • 3, only after a valid input character entered behind the blank as a separator or terminator.
  • next () String with spaces can not be obtained.

nextLine():

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

Note:

To enter data type int or float, in the Scanner class is also supported, but it is preferable to use hasNextXxx () method was validated before entering, reuse nextXxx () to read:

Published 49 original articles · won praise 6 · views 10000 +

Guess you like

Origin blog.csdn.net/ZGL_cyy/article/details/104089581