一.什么是Scanner
1)来自java.util.Scanner库,用来获取用户的输入。
2)基本语法 :
Scanner scan = new Scanner(System.in);
…
scan.close();
二.各种类型的输入
1)字符串输入
–>next()方法
Scanner scan = new Scanner(System.in);
if (scan.hasNext()) //判断是否有输入
{
String s = scan.next(); //获取输入字符串
}
scan.close();
–>nextLine()方法
Scanner scan = new Scanner(System.in);
if (scan.hasNextLine()) //判断是否有输入
{
String s = scan.nextLine(); //获取输入字符串
}
scan.close();
区别:
内容 | next() | nextLine() |
---|---|---|
结束标志 | 遇到空格就结束输入 | 遇到Enter换行符结束输入 |
能否含有空格 | 不能 | 能 |
2)整型输入
–>nextInt()
Scanner scan = new Scanner(System.in);
if (scan.hasNextInt()) //判断是否有输入
{
int s = scan.nextInt(); //获取输入字符串
}
scan.close();
3)浮点数输入
–>nextFloat()
Scanner scan = new Scanner(System.in);
if (scan.hasNextFloat()) //判断是否有输入
{
float s = scan.nextFloat(); //获取输入字符串
}
scan.close();