Java Scanner 類——獲取用戶的輸入

建立Scanner對象語法

Scanner scan = new Scanner(System.in);java

使用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();
    }
}

以上兩者區別spa

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

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...blog

相關文章
相關標籤/搜索