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