java无法输入字符串问题

问题描述:

今天重温java知识遇见的小问题,使用 sc.nextLine(); 语句输入字符串时竟然会直接跳过,无法输入,如下图所示:

Scanner sc = new Scanner(System.in);
System.out.println("请输入机票原价");
int price= sc.nextInt();
System.out.println("请输入月份");
int mouth=sc.nextInt();
System.out.println("请输入车票类型");
String type=sc.nextLine();
System.out.println(type);

问题原因:

经搜索得知这个问题出现在将sc.nextInt()和sc.nextLine()连用上,前者会以enter字符作为结尾,且不会再执行后移除,因此enter被保留下来作为后者的输入,导致直接跳过。

解决方法:

再加一个sc.nextLine()即可,如图所示:

Scanner sc = new Scanner(System.in);
System.out.println("请输入机票原价");
int price= sc.nextInt();
System.out.println("请输入月份");
int mouth=sc.nextInt();
System.out.println("请输入车票类型");
sc.nextLine();
String type=sc.nextLine();
System.out.println(type);

tips:这个设计感觉也会在别的地方出现错误,如果有老司机碰到希望可以留言告知派个雷;如果有其余的解决方法也希望能告知,感谢感谢

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值