1. 程式人生 > 其它 >Scanner用法

Scanner用法

技術標籤:java

一、基本用法

  • 接收鍵盤資料的方法:next()、nextLine()

  • 判斷是否還有輸入的資料的方法:hasNext()、hasNextLine()

示例

  • 示例1-- next()與hasNext()
import java.util.Scanner;
public class Demo01{
    public static void main(String[] args) {
        
        //定義掃描器物件,用於接收鍵盤資料
        Scanner sc = new Scanner(System.in);
        
        System.
out.println("next接收資料:"); if(sc.hasNext()){ String str = sc.next(); System.out.println("使用者輸入的內容為:"+str); } //凡是屬於IO流的類如果不關閉會一直佔用資源 sc.close(); } }

測試結果:

next


  • 示例2–nextLine()與hasNextLine()
import java.util.Scanner;
public class
Demo02{ public static void main(String[] args) { //定義掃描器物件,用於接收鍵盤資料 Scanner sc = new Scanner(System.in); System.out.println("nextLine接收資料:"); if(sc.hasNextLine()){ String str = sc.nextLine(); System.out.println("輸入的內容為:"
+str); } //關閉IO流 sc.close(); } }

測試結果:

nextLine

結果分析

next():

  • 只有輸入有效字元後才將其後面輸入的空白作為結束符(若只輸入空格,輸入不會結束)

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

    (讀取字串" hello world"與"hello world"的結果是一樣的,都只讀取了"hello")

  • 以空格為結束符

nextLine():

  • 以回車為結束符,–nextLine()方法返回的是輸入回車之前的所有字元
  • 可以獲得空格

二、判斷使用者輸入型別

nextInt()、nextFloat()、nextDouble()…

hasNextInt()、hasNextFloat、hasNextDouble()…

示例

import java.util.Scanner;
public class Demo03{
    public static void main(String[] args) {
        
        Scanner sc = new Scanner(System.in);
        
        System.out.println("請輸入數字:");
        
        if(sc.hasNextInt()){
            int num = sc.nextInt();
            System.out.println("輸入的整數為:"+num);
        }
        else if(sc.hasNextFloat()){
            Float num = sc.nextFloat();
            System.out.println("輸入的為浮點數:"+num);
        }
        else {
            System.out.println("不是整數也不是浮點數");
        }
        
        sc.close();
    }
}

測試結果:

  • 輸入整數時:

scanner-judge-01

  • 輸入浮點數時:

judge02

  • 其他:

scanner-judge-03

注:

判斷輸入型別的函式還有很多,具體可查閱api文件

api文件連結: