如果未定义输入的长度,如何从 std.in 中读取
How to read from std.in if the length of the input is not define
我在使用扫描仪从 java 中的标准输入读取输入时遇到问题。我需要读取用户输入并将其放入动态数组中。这是输入示例:
4 6
2 3
4 8
9 5
还有我的代码:
Scanner scan = new Scanner(System.in);
List<int[]> temp = new ArrayList<>();
int[] couple = new int[2];
int current = 0;
while (scan.hasNextInt()) {
if (current == 2) {
temp.add(couple);
current = 0;
couple = new int[2];
}
couple[current] = scan.nextInt();
current++;
}
scan.close();
我做错了什么?
您做的一切都正确,但您没有将最后一对添加到列表中。您可以通过在循环后添加此代码来解决此问题:
if (current == 2) {
temp.add(couple);
}
不过,您的方法并不理想:与其一次读取一个整数,不如成对读取它们,如下所示:
while (true) {
if (!scan.hasNextInt()) break;
int first = scan.nextInt();
if (!scan.hasNextInt()) break;
int second = scan.nextInt();
temp.add(new int[] { first, second });
}
您在输入时是否在整数之间使用空格?如果是这样,那将是一个问题,因为空格是字符或字符串而不是整数。
我在使用扫描仪从 java 中的标准输入读取输入时遇到问题。我需要读取用户输入并将其放入动态数组中。这是输入示例:
4 6
2 3
4 8
9 5
还有我的代码:
Scanner scan = new Scanner(System.in);
List<int[]> temp = new ArrayList<>();
int[] couple = new int[2];
int current = 0;
while (scan.hasNextInt()) {
if (current == 2) {
temp.add(couple);
current = 0;
couple = new int[2];
}
couple[current] = scan.nextInt();
current++;
}
scan.close();
我做错了什么?
您做的一切都正确,但您没有将最后一对添加到列表中。您可以通过在循环后添加此代码来解决此问题:
if (current == 2) {
temp.add(couple);
}
不过,您的方法并不理想:与其一次读取一个整数,不如成对读取它们,如下所示:
while (true) {
if (!scan.hasNextInt()) break;
int first = scan.nextInt();
if (!scan.hasNextInt()) break;
int second = scan.nextInt();
temp.add(new int[] { first, second });
}
您在输入时是否在整数之间使用空格?如果是这样,那将是一个问题,因为空格是字符或字符串而不是整数。