004_wz_bbk_用GCC編譯第一個C程式及多檔案程式設計
阿新 • • 發佈:2021-02-02
Scanner
Scanner類是獲取使用者輸入,通過Scanner類的next()與nextLine()方法獲取輸入的字串,用hasNext()與hasNextLine()判斷是否還有輸入的資料。
next()與nextLine()的區別:
next()不能得到帶有空格的字串。
nextLine()以Enter為結束符,也就是說nextLine()方法返回的是輸入回車之前的所有字元。可以獲得空白。
next():
public class Demo01 {
public static void main(String[] args){
//建立一個掃描器物件,用於接收鍵盤資料
Scanner scanner = new Scanner(System.in);
System.out.println("使用next方式接收:");
//判斷使用者有沒有輸入字串
if(scanner.hasNext()){
String str= scanner.next();
System.out.println("輸出的內容為:"+str);
}
//凡是屬於IO流的類如果不關閉就會一直佔用資源,要養成好習慣用完就關掉
scanner.close();
}
輸出結果:
nextLine():
public class Demo02 {
public static void main(String[] args){
Scanner scanner=new Scanner(System.in);
System.out.println("使用nextLine方式接收:");
if(scanner.hasNextLine()){
String str=scanner.nextLine();
System. out.println("輸出的內容為:"+str);
}
scanner.close();
}
}
輸出結果: