【发布时间】:2021-03-06 18:23:02
【问题描述】:
我希望将以下 String ArrayList 读入 Int 类型的 ArrayList:
[1000, 31000, 3, Texas, 1042, 12180.06, 3, Texas, 1062, 13240.45, 2, Texas, 1200, 36000, 2, Maryland, 1327, 19800.56, 2, Alaska, 1483, 22458.23, 7, Texas, 1900, 17000.09, 3, Washington, 2000, 16910.00, 2, Vermont, 2112, 23125, 4, Alaska, 2500, 20001, 5, Hawaii, 3000, 21330.00, 3, Texas, 3210, 13200, 1, Minnesota, 3600, 77500, 4, California, 3601, 11970, 2, Illinois, 4000, 25750.00, 4, Florida, 4724, 8900, 3, Oklahoma, 6217, 45000.70, 2, Texas, 9280, 6200, 1, Vermont, 5000, 30170.00, 2, Hawaii, 5100, 30170.05, 5, Arkansas, 5601, 51970, 9, Illinois, 5724, 66900, 3, Florida, 5217, 10002.68, 2, Texas, 5280, 70000, 1, Washington, 5000, 100000, 10, Hawaii, 5200, 25000.4, 3, Texas, 5230, 120000, 6, California, 6641, 85000, 7, Alaska, 7000, 45500, 4, Maryland, 7100, 56500, 3, Illinois, 7205, 50100.65, 8, Arkansas, 8110, 110005.9, 8, Texas, 8340, 70100.25, 9, Iowa, 9101, 67590.40, 6, Texas, 9220, 35000.58, 8, Arkansas, 9300, 22000.69, 4, Iowa, 9400, 19490.00, 1, Hawaii, 9400, 55490.00, 4, Pennsylvania]
有没有办法读取每第四个元素,以便将 31000、12180.06、13240.45、36000、...等读入 ArrayList 收入,转换为 int 数据类型?
我来自 Python 并且是 Java 新手,不知道如何正确地做到这一点。以下代码正在输出从 1 开始的每四个数字的列表...
List<String> surveyData = new ArrayList<String>(Arrays.asList(contents.split("\\s+")));
ArrayList<Integer> income = new ArrayList<>();
for (int i = 1; i < surveyData.size(); i+=4)
{
income.add(i);
}
System.out.println(income);
当前输出:
[1, 5, 9, 13, 17, 21, 25, 29, 33, 37, 41, 45,...]
预期输出:
[31000, 12180.06, 13240.45, 36000, 19800.56... ]
将数据存储到 ArrayList 非常重要!
***更新 以这种格式从文件中读取数据:
1000 31000 3 Texas
1042 12180.06 3 Texas
1062 13240.45 2 Texas
1200 36000 2 Maryland
1327 19800.56 2 Alaska
1483 22458.23 7 Texas
1900 17000.09 3 Washington
...
使用此代码:
public void readFile()
{
String contents = null;
try
{
contents = new String(Files.readAllBytes(Paths.get("Program10.txt")));
}
catch (IOException e)
{
e.printStackTrace();
}
List<String> surveyData = new ArrayList<String>(Arrays.asList(contents.split("\\s+")));
double[] income = new double[surveyData.size()];
double sum = 0;
for (int i = 0; i < surveyData.size(); i+=4)
{
income[i] = Double.parseDouble(surveyData.get(i));
sum += income[i];
}
// Calculate & Print the Average Income
averageIncome = sum / (income.length / 4);
// Outputting the total rainfall for the year
System.out.printf("%nAverage Income is %.2f", averageIncome);
打印正确的平均值(我检查过)并将所有其他项目解析为 0.0。请注意,我有 income.length / 4 来跳过无关的元素。
【问题讨论】:
-
可能重复(根据你对 Python 的经验,你可能对流/函数式风格很熟悉……在 Java 中,很容易将列表转换为流):stackoverflow.com/questions/31602425跨度>