什麼是Scanner?next()和hasNext() ? nextLine()和hasNextLine()?
阿新 • • 發佈:2018-11-23
java.util.Scanner 是 Java5 的新特徵,我們可以通過 Scanner 類來獲取使用者的輸入。
Scanner sc = new Scanner(System.in);
通過 Scanner 類的 next() 與 nextLine() 方法獲取輸入的字串,在讀取前我們一般需要 使用 hasNext 與 hasNextLine 判斷是否還有輸入的資料:
next() -->hasNext()
nextLine() ---->hasNextLine()
next方法
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();
}
}
輸出:
$ javac ScannerDemo.java
$ java ScannerDemo
next方式接收:
runoob com
輸入的資料為:runoob
nextLine()方法
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();
}
}
輸出:
$ javac ScannerDemo.java
$ java ScannerDemo
nextLine方式接收:
runoob com
輸入的資料為:runoob com
next()與nextLine()比較:
next():
- 1、一定要讀取到有效字元後才可以結束輸入。
- 2、對輸入有效字元之前遇到的空白,next() 方法會自動將其去掉。
- 3、只有輸入有效字元後才將其後面輸入的空白作為分隔符或者結束符。
- 4、next() 不能得到帶有空格的字串。
nextLine():
- 1、以Enter為結束符,也就是說 nextLine()方法返回的是輸入回車之前的所有字元。
- 2、可以獲得空白。
