今天在牛客网做题,题目是先输入数字n,然后输入n个串,结果每次能够输入的串都是n-1,后来发现,nextInt不会自动换行,因此提供一些解决方法。
方法一:以串读入,转为int
Scanner sc = new Scanner(System.in);
Integer num = Integer.parseInt(sc.nextLine());
String[] strArr = new String[num];
for (int i=0; i<num; i++) {
strArr[i] = sc.nextLine();
}
方法二:在nextInt后读入一个换行
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
sc.nextLine();
String[] strArr = new String[num];
for (int i=0; i<num; i++) {
strArr[i] = sc.nextLine();
}