Scanner的一些用法
1、Scanner对象的创建
首先要确保导入了Scanner包
import java.util.Scanner;
创建Scanner对象:
Scanner scanner = new Scanner(System.in);
2、Scanner对象的一些方法
- nextInt():只能读取int整数类型数据,输入其他非整型数据会报错。nextFloat()、nextDouble()等方法也是如此。
Scanner sc = new Scanner(System.in);
System.out.println("请输入年龄:");
int age = sc.nextInt();
-
next()与nextLine()的区别
next():
一定要读取到有效字符后才可以结束输入;
对于输入有效字符之前的空白,会自动去掉;
对于有效字符后面输入的空白,会将其当做分隔符或者结束符
next()不能得到带有空格的字符串
public class ScannerDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入带有空白的字符串:");
String str = sc.next();
System.out.println("输入的字符串为:"+str);
sc.close();
}
}
//运行结果如下
请输入带有空白的字符串:
hello Java
输入的字符串为:hello
上述代码中输入的字符串没有完全打印,因为hello Java中间带有空格,该空格被当做了输入结束符。
nextLine():
以Enter作为结束符,该方法返回的是输入回车之前的所有字符。
可以得到空白。
public class ScannerDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入带有空白的字符串:");
String str1 = sc.nextLine();
System.out.println("输入的字符串为:"+str1);
sc.close();
}
}
//运行结果如下
请输入带有空白的字符串:
HELLO JAVA
输入的字符串为:HELLO JAVA