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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM