【问题标题】:How would I determine whether a state lost or grew in population?我如何确定一个州的人口是减少还是增加?
【发布时间】:2017-11-06 00:09:11
【问题描述】:

我正在使用分隔符来读取两个不同的文件,一个用逗号分隔,另一个用制表符分隔。我将这些文件放入两个数组列表中。现在我想通过说哪些州失去人口(我相信应该只是密歇根州)和哪些州增加来比较它们。

package delim;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;

public class MyMain {

    public static void main(String[] args) throws IOException {
        File fi = new File("2010census.txt");
        File fil = new File("2000census.txt");
        Scanner sc = new Scanner(fi).useDelimiter("[|,|\n|\r]+");
        Scanner kb = new Scanner(fil).useDelimiter("[\t|\n|\r]+");
        String stateName;
        int numb;
        ArrayList<Integer> arrL = new ArrayList<Integer>();
        ArrayList<Integer> arrL2 = new ArrayList<Integer>();

        //while loop to read 2000 census
        while (kb.hasNext()) {
            stateName = kb.next();
            numb = kb.nextInt();
            System.out.println(stateName + " " + numb);
            arrL.add(numb);
        }
        //while loop to read 2010 census
        while (sc.hasNext()) {
            stateName = sc.next();
            numb = sc.nextInt();
            System.out.println(stateName + " " + numb);
            arrL2.add(numb);
        }
    }
}

【问题讨论】:

  • 从 Apache Commons 获取一个 csv 阅读器。

标签: java arrays list delimiter


【解决方案1】:

您需要使用 HashMap 将状态链接到值。您将在读取 csv 之前声明哈希图,并且 map.put 将在循环中,同时读取您的 csv

HashMap<String,Integer> hm2000 = new HashMap<String,Integer>(); 
HashMap<String,Integer> hm2010 = new HashMap<String,Integer>(); 

// Add to hashmap
map.put("<state>", population); 

然后按键遍历其中一个,与另一个 hashmap 进行比较

for(Map.Entry<Integer, Book> entry:hm2000.entrySet()){    
    int key=entry.getKey();  
    // Compare the value from the other hashmap, store it in an array / 
    // other hashmap for reporting at the end
    ...
}

现在您可以对数据做任何您想做的事情。

注意:这不是最优雅的方式,但对你来说应该是一个好的开始。

【讨论】:

    猜你喜欢
    • 2021-08-25
    • 2022-08-18
    • 2017-11-16
    • 1970-01-01
    • 2020-03-08
    • 1970-01-01
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多