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