Scanner 和 Switch case

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
也就是穿透使用。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值