java - 扫描仪无法从控制台读取 int 后的字符串?
问题描述
我正在使用 Scanner 对象从控制台读取值。如果我连续读取 2 个字符串,一切正常:
Scanner sc = new Scanner(System.in);
System.out.println("Enter the first string");
String first = sc.nextLine();
System.out.println("Enter the second string");
String second = sc.next();
但是,如果我尝试先读取 Integer,然后再读取这两个字符串:
Scanner sc = new Scanner(System.in);
System.out.println("Enter num");
int a = sc.nextInt();
System.out.println("Enter the first string");
String first = sc.nextLine();
System.out.println("Enter the second string");
String second = sc.nextLine();
System.out.println("First '" + first + "'; second '" + second + "'");
然后行 String first = sc.nextLine(); 没有写在变量中,以某种方式跳过=/
检查控制台输出:
Enter num
123 //(it is input)
Enter the first string
Enter the second string //(This and previous line appear together)
Str //(Only one line appears for input)
First ''; second 'Str'
在调试中,我提供输入第一个字符串,我输入它,然后在下一步调试器将此变量显示为空字符串。
它应该像这样工作吗?
解决方案
推荐阅读
- jenkins - 如何在 Jenkins SCM 管道中定义参数化的 SVN url
- c - 关于UNIX中复制和删除(cp,rm)的问题
- python - 有人可以帮我解决错误吗:TypeError: +: 'NoneType' and 'NoneType' 不支持的操作数类型
- rpa - 如何下载旧版本的 UiPath Studio?
- cmake - DPDK 示例应用程序编译错误缺少库文件
- python - 滚动回归:ValueError:endog 必须具有 ndim 1 但具有 ndim 2
- c# - 如何在 .NET Core 中使用 VPC 端点连接 AWS 机密管理器?
- c# - 我想用 OxyPlot 来实现一个自定义的 X 轴标签,就像这样。X 轴只显示数据点的值。这在 oxyPlot 中可能吗?
- forms - 添加和删除上传文件集合中的项目
- javascript - ng boostrap 日期选择器将日期绑定到表单控件(getFullYear 不是函数)