天天看點

Java Scanner 類——擷取使用者的輸入

建立Scanner對象文法

Scanner scan = new Scanner(System.in);

使用next()擷取輸入的字元串

import java.util.Scanner;

public class ScanTest1 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        if (scanner.hasNext()) {
            String str1 = scanner.next();
            System.out.println("Input:" + str1);
        }
        scanner.close();
    }
}      

使用nextLine()擷取字元串

public class ScanTest2 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        if (scanner.hasNextLine()) {
            String str1 = scanner.nextLine();
            System.out.println("Input:" + str1);
        }
        scanner.close();
    }
}      

以上二者差別

nextLine()見到回車就結束,而next()必須得到有效字元

next()擷取第一個空格前資料(比如,輸入a b c得到a,輸入  a b得到a)

使用nextInt()擷取整數

public class ScanTest3 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        if (scanner.hasNextInt()) {
            int str1 = scanner.nextInt();
            System.out.println("Input:" + str1);
        }
        scanner.close();
    }
}      

同樣,還有nextShort, nextFloat, nextDouble, nextBoolean, nextByte,  nextChar, nextBigInteger, nextBigDecimal...