一敞映、
創(chuàng)建 Scanner 對(duì)象的基本語法:
Scanner s = new Scanner(System.in);
1.使用 next 方法:
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// 從鍵盤接收數(shù)據(jù)
// next方式接收字符串
System.out.println("next方式接收:");
// 判斷是否還有輸入
if (scan.hasNext()) {
String str1 = scan.next();
System.out.println("輸入的數(shù)據(jù)為:" + str1);
}
scan.close();
}
}
2.使用 nextLine 方法:
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
// 從鍵盤接收數(shù)據(jù)
// nextLine方式接收字符串
System.out.println("nextLine方式接收:");
// 判斷是否還有輸入
if (scan.hasNextLine()) {
String str2 = scan.nextLine();
System.out.println("輸入的數(shù)據(jù)為:" + str2);
}
scan.close();
}
}
二揖铜、
next() 與 nextLine() 區(qū)別
next():
1颂翼、一定要讀取到有效字符后才可以結(jié)束輸入岂膳。
2秫逝、對(duì)輸入有效字符之前遇到的空白古程,next() 方法會(huì)自動(dòng)將其去掉。
3屯伞、只有輸入有效字符后才將其后面輸入的空白作為分隔符或者結(jié)束符腿箩。
next() 不能得到帶有空格的字符串。
nextLine():
1劣摇、以Enter為結(jié)束符,也就是說 nextLine()方法返回的是輸入回車之前的所有字符珠移。
2、可以獲得空白饵撑。
三剑梳、