gpt4 book ai didi

java - 将数据文件中的整数存储到数组 Java 中

转载 作者:行者123 更新时间:2023-12-01 22:10:38 25 4
gpt4 key购买 nike

我正在尝试将数据文件中的整数存储到数组中。我正在使用 Java Eclipse IDE。

这是我的数据文件:

(oddsAndEvens.dat)

2 4 6 8 10 12 14
1 2 3 4 5 6 7 8 9
2 10 20 21 23 24 40 55 60 61

这是我的代码:

import java.io.File;
import java.util.Arrays;
import java.io.IOException;
import java.util.Scanner;

public class OddsAndEvens {
public static void main(String[] args) throws IOException {
Scanner file = new Scanner(new File("oddsAndEvens.dat"));
int count, num = 0;
int[] newRay = null;
while (file.hasNext()) {
String line = file.nextLine();
Scanner chop = new Scanner(line);
count = 0;
while (chop.hasNextInt()) {
num = chop.nextInt();
count++;

newRay = new int[count];
int j = 0;
for (int i = 0; i < count; i++) {
newRay[j] = num;
j++;
}
}
System.out.println(Arrays.toString(newRay));
}
}
}

我的输出如下:


[14, 14, 14, 14, 14, 14, 14]
[9, 9, 9, 9, 9, 9, 9, 9, 9]
[61, 61, 61, 61, 61, 61, 61, 61, 61, 61]

我正在寻找的是:

[2, 4, 6, 8, 10, 12, 14]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[2, 10, 20, 21, 23, 24, 40, 55, 60, 61]

如何将数据文件中每行的这些数字组转换为数组?有更简单的方法吗?

最佳答案

您可以读取每一行并将其存储在字符串数组中,方法是将其用空格分割,然后将其转换为整数,以下是您的操作方法。\

import java.io.File;
import java.util.Arrays;
import java.io.IOException;
import java.util.Scanner;

public class OddsAndEvens {
public static void main(String[] args) throws IOException {
Scanner file = new Scanner(new File("oddsAndEvens.dat"));
int[] newRay = null;
while (file.hasNext()) {
String line = file.nextLine();
String[] str = line.split("\\s+");
newRay = new int[str.length];
for (int i = 0; i < str.length; i++) {
newRay[i] = Integer.valueOf(str[i]);
}
System.out.println(Arrays.toString(newRay));
}
}
}

关于java - 将数据文件中的整数存储到数组 Java 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58661987/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com