Scanner
在使用中发现一个问题,在系统输入一个int类型数据就会停止,并且只会输出那个int类型数据。如果先输入字符串类型在输入int类型则不会报错。
例如 :
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
String b=sc.nextLine();
控制台只会输出a 的值,b的值就会没有输出.
解决方法有三种:
1,如果系统先输入的是int类型的值,再输入String类型的值,那么只会输出int类型数据
String a=sc.nextLine();
int a2=Integer.parseInt(a);//转换为int类型
String b=sc.nextLine();
这样就可以解决问题
2,第二种方法
int a=sc.nextInt();
sc.nextLine();//一定要是sc.nextLine();才行
String b=sc.nextLine();
System.out.println(a);
System.out.println(b);
这种也可以
3,第三种方法
Scanner sc=new Scanner(System.in);
Scanner sb=new Scanner(System.in);
while(sc.hasNext()) {
int a=sc.nextInt();
String b=sb.nextLine();
System.out.println(a);
System.out.println(b);
}
这种多一点不过也可以解决。
Switch case
是个循环语句,在使用过程中也学到了新的用法,穿透型。
例如:
int a = 1;
int num = 0;
switch(a){
case 3 :
num++;
case 2 :
num++;
case 1:
num++;
default:
System.out.println("---------");
}
System.out.println(num);
当a等于1时,num输出的值是1
当a等于3时,num输出的值是3
也就是穿透使用。
Scanner 和 Switch case
最新推荐文章于 2023-03-11 06:50:10 发布