我想将两个字符串输入放入字符串数组
String[] b = new String[n];
通过使用扫描仪,但扫描仪会自动读取空白值
b[0]
.即它会跳过第一个循环。
Scanner scn = new Scanner(System.in);
int no = 0;
int n = scn.nextInt();
String[] b = new String[n];
for (int j = 0; j < n; j++) {
System.out.println("Enter the string");
b[j] = scn.nextLine();
}
输出类似于
2
Enter
Enter
abc
谁能告诉我为什么会出现这个问题?
最佳答案
这是因为 nextInt()
不会读取您输入中的 \n
。然后由您的 nextLine()
更多解释,
当您在 nextInt()
调用提示时输入数字时。您输入一个数字并按 Enter 这使您的输入看起来像这样
10
\n
nextInt()
仅读取 10
并忽略 \n
。
然后,您的 nextLine()
仅读取 \n
。
这解释了您的输出。
您可以通过在 nextInt()
之后添加一个额外的 nextLine()
来获得预期的输出。
参见this了解更多信息。
关于java - 扫描仪将空白作为输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32495429/