问题描述:
今天重温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:这个设计感觉也会在别的地方出现错误,如果有老司机碰到希望可以留言告知派个雷;如果有其余的解决方法也希望能告知,感谢感谢