import java.util.Scanner;
public class test {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int num = input.nextInt();
String[] strArr = new String[num];
arrStrMaker(strArr);
}
public static void arrStrMaker(String[] arr){
for (int i = 0; i < arr.length; i++) {
System.out.println("String for index ["+i+"]");
arr[i] = input.nextLine();
System.out.println(arr[i]);
}
}
}
输出:
3
String for index [0]
String for index [1]
注意它如何完全忽略索引 0 中的输入,并向索引 0 中“插入”任何内容
import java.util.Scanner;
public class test {
public static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int num = 3;
String[] strArr = new String[num];
arrStrMaker(strArr);
}
public static void arrStrMaker(String[] arr){
for (int i = 0; i < arr.length; i++) {
System.out.println("String for index ["+i+"]");
arr[i] = input.nextLine();
System.out.println(arr[i]);
}
}
}
输出:
索引 [0] 的字符串
*注意它如何没有忽略索引 0 并等待输入。
问题出在哪里?
当我使用 int num = input.nextInt();
时忽略索引 0。
当我使用 int num = 3;
时,等待索引 0 处的输入。
最佳答案
nextLine
和 nextInt
(事实上,nextLine
和任何其他非 nextLine
的 next-anything
调用)交互很奇怪。我建议你这样做:
`input.useDelimiter("\r?\n");`
创建扫描仪后(new Scanner(...)
),每次创建扫描仪时,然后使用 next()
而不是 nextLine()
。这会将“分隔符”设置为仅换行符,因此现在每次用户按 Enter 键时,扫描仪都会为您提供 1 个标记;这通常就是您想要从扫描仪获得的结果。
关于java - 字符串数组在 for 循环中初始化时忽略索引 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59529318/