我试图从扫描仪获取输入并将值分配到一个字符串数组中,循环必须运行 3 次,但它只接受两个输入。谁能解释一下为什么这不接受 3 个输入并显示相同的内容。
import java.util.Arrays;
import java.util.Scanner;
public class DimentionalArray {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int size = sc.nextInt(); // ex, if size is 3
String[] str = new String[size];
for (int i = 0; i < str.length; i++) {
str[i] = sc.nextLine();
}
Arrays.stream(str).forEach(e -> {System.out.println(e);});
}
}
例如。 我的输入是
3 //size 1 2 // 1st input 3 4 //2nd input 4 5 // 3rd input
但它没有读取输入,并且在读取第二个输入(3 4)后关闭。 谁能解释一下为什么这不读取第三个元素。
最佳答案
只需添加
sc.nextLine();
在int size = sc.nextInt()之后;
关于java - 在java中从扫描仪读取输入到字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58961339/