java.util.Scanner是Java5的新特征,我们可以通过Scanner类来获取对象的输入。
- 基本语法
Scanner scanner = new Scanner(System.in);
可以通过Scanner类的next(),nextLine()方法获取输入字符,
在读取前我们一般使用hasNext(),hasNextLine()来判断是否有输入的数据。
- 用next()方式接受
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
//创建一个扫描器对象,用于接受键盘数据
Scanner scanner = new Scanner(System.in);
System.out.println("用next()方式接受:");
//判断用户有没有输入数据
if (scanner.hasNext()) {
String str = scanner.next();
System.out.println("输入的内容为:"+str);
}
//但凡属于IO流的类如果不进行关闭,就会一直占用资源。
scanner.close(); //关闭scanner
}
}
- 用nextLine()方式接受
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
//创建一个扫描器对象,用于接受键盘数据
Scanner scanner = new Scanner(System.in);
System.out.println("用nextLine()方式接受:");
//判断用户有没有输入数据
if (scanner.hasNextLine()) {
String str = scanner.nextLine();
System.out.println("输入的内容为:"+str);
}
//但凡属于IO流的类如果不进行关闭,就会一直占用资源。
scanner.close(); //关闭scanner
}
}
- 结果
同样输入“hello word”
![](https://img.haomeiwen.com/i8413975/6892f598bbaf36e8.png)
![](https://img.haomeiwen.com/i8413975/20a62bfcd66c83db.png)
nextLine()可以获取空白,以Enter为结束符
next()读到有效字符后才可以结束输入·,不能得到带有空格的字符串。
- 练习
输入多个数字,求其和与平均数,输入非数字已结束输入
public class Demo01 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double sum = 0;
double x = 0;
int m = 0;
while (scanner.hasNextDouble()){ //判断是否为double,不是则跳出循环
x = scanner.nextDouble();
m++;
sum = sum + x;
}
System.out.println("总和为:"+sum);
System.out.println("平均数:"+(sum/m));
}
}
网友评论