Scanner类
java.util.Scanner 是 Java5 的新特征,我们可以通过 Scanner 类来获取用户的输入。
下面是创建 Scanner 对象的基本语法:
Scanner s = new Scanner(System.in);
1.运行示例
接下来我们演示一个最简单的数据输入,并通过 Scanner 类的 next() 与 nextLine() 方法获取输入的字符串,运行的代码如下:
package com.zj.Demo;
import java.util.Scanner;
public class Demo03 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入成绩:");
int score = sc.nextInt();
if(score==100){
System.out.println("满分");
}else if(score>=90&&score<100){
System.out.println("优秀");
}else if(score>=80&&score<90){
System.out.println("合格");
}else if(score>=70&&score<80){
System.out.println("要努力");
}else if(score>=60&&score<70){
System.out.println("再接再厉");
}else if(score>=0&&score<60){
System.out.println("不及格");
}else {
System.out.println("输入成绩有误");
}
sc.close();
}
}
2.运行结果
执行以上的代码输出的结果如下所示:
3.next() 与 nextLine() 区别
- next():
1、一定要读取到有效字符后才可以结束输入。
2、对输入有效字符之前遇到的空白,next() 方法会自动将其去掉。
3、只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符。
next() 不能得到带有空格的字符串。
- nextLine():
1、以Enter为结束符,也就是说 nextLine()方法返回的是输入回车之前的所有字符。
2、可以获得空白。