Scanner——Java基礎

20170405發表於2020-07-21

  Scanner

  基本語法

  Scanner s = new Scanner(System.in);

  透過Scanner類的 next() 和 nextLine() 方法獲取輸入的字串,在讀取前一般使用 hasNext() 和 hasNextLine() 判斷是否還有輸入的資料。

  使用 next 方法:

  Scanner scan = new Scanner(System.in);

  // 從鍵盤接收資料

  // next方式接收字串

  System.out.println("next方式接收:");

  // 判斷是否還有輸入

  if (scan.hasNext()) {

  String str1 = scan.next();

  System.out.println("輸入的資料為:" + str1);

  }

  scan.close();

  next() 方法:

  一定要讀取到有效字元後才可以結束輸入。

  對輸入有效字元之前遇到的空白,next() 方法會自動將其去掉。

  只有輸入有效字元後才將其後面輸入的空白作為分隔符或者結束符。

  next() 不能得到帶有空格的字串。

  使用 nextLine 方法:

  Scanner scan = new Scanner(System.in);

  // 從鍵盤接收資料

  // nextLine方式接收字串

  System.out.println("nextLine方式接收:");

  // 判斷是否還有輸入  

  if (scan.hasNextLine()) {

  String str2 = scan.nextLine();

  System.out.println("輸入的資料為:" + str2);

  }

  scan.close();

  nextLine() 方法:

  以Enter為結束符,也就是說 nextLine() 方法返回的是輸入回車之前的所有字元。

  可以獲得空白。

  如果要輸入 int 或 float 型別的資料,在 Scanner 類中也有支援,但是在輸入之前最好先使用 hasNextXxx() 方法進行驗證,再使用 nextXxx() 來讀取。

  SA版權協議,轉載請附上原文出處連結及本宣告。


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69979119/viewspace-2705957/,如需轉載,請註明出處,否則將追究法律責任。

相關文章