我是 java 的新手。这是我的代码。我使用扫描仪通过 nextint 方法确定了我的字符串数组大小。然后我用下一行方法添加了字符串。这对我来说似乎是正确的,但我看不到数组的第一个值。这段代码有什么问题。
public class App {
public static void main(String[] args) {
String[] arr;
Scanner sc = new Scanner(System.in);
System.out.println("write a number ");
int n = sc.nextInt();
arr = new String[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextLine();
}
System.out.println(arr[0]);
}
}
最佳答案
您可以看到第一个条目,它恰好是一个空白String
。
发生这种情况的原因是,当您调用 int n = sc.nextInt();
并且用户按下 Enter 时,Scanner
读取整数,但将行尾字符留在缓冲区中。
当您使用 sc.next()
读取第一个字符串时,行尾“剩余”会立即被扫描,并作为第一个 String< 呈现给您的程序
空白。
这个问题的修复很简单:在 sc.nextInt()
之后调用 sc.next()
,并忽略结果。
关于java - 数组的第一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34700122/