Scanner()类:
作用:起一个数据传递的作用,不用Scanner()时,数据需要在代码中输入(感觉跟静态的方式一样,数据值已经定义好了);使用了Scanner(),可以在控制台中输入数据(感觉变成了动态的方式)。
具体用法:Scanner sc = new Scanner(System.in);
然后sc对象(上面定义的对象)调用下列方法(函数),读取用户在命令行输入的各种数据类型:hasnext.Byte(),hasnextDouble(),hasnextFloat(),hasnextInt(),hasnextLin(),hasnextLong(),hasnextShot()
这些用来判断输入的数据是否符合定义的数据类型,符合true(数据输入),不符合false(数据不执行任何输入)
比如:hasnextInt(); 判断输入的是否为整数,这时候如果不是整数,他就不会输入这个数据。
例子:有N个人坐在一起,第一个人年龄为10,后面人的年龄比前一个人大2岁,求第N个人的年龄是多少。
不使用scanner:
public class PersonAge {
public static void main(String[] args) {
int sum = 0;
int n = 0;//输入这个n表示的就是N个人,通过这里输入数据
if (n > 0){
for (int i = 0; i < n; i++) {
sum = 10 + (n-1)*2;
}
System.out.println("第"+n+"个人的年龄为:"+sum);
}
else{
System.out.println("输入的数字不符合要求!");
}
}
}
使用scanner:
import java.util.Scanner;
public class PersonAgeScanner {
public static void main(String[] args) {
System.out.println("输入人数n,按非数字键结束");//文字提示用户输入数据
Scanner sc = new Scanner(System.in); //使用scanner类
int n = 0; //属性
int sum = 0;
while(sc.hasNextInt()){ //定义的对象“.”(调用)hasNextInt()方法判断输入数据是否符合要求
n = sc.nextInt(); //传递参数
sum = 10 + (n-1)*2; //程序
System.out.println("第"+n+"个人的年龄为:"+sum);
}
}
}