将2D字符串数组解析为2D int数组

时间:2014-02-04 00:22:30

标签: java arrays sorting

我正在寻找一种方法来关联此文件(csv)中的每一行,并采用与商店名称相关联的每月最大值(每列代表月份)。我可以获得行最大值和列最大值,但我不知道如何将每列最大值链接到其城市名称。求救!

这是文件:

Omaha,104,1218,418,216,438,618,274,234,510,538,740,540
Saint Louis,72,1006,392,686,626,670,204,286,236,344,394,930
Des Moines,116,1226,476,330,444,464,366,230,602,260,518,692
Chicago,408,948,80,472,626,290,372,282,488,456,376,580
Kansas City,308,1210,450,234,616,414,500,330,486,214,638,586
Austin,500,812,226,470,388,488,512,254,210,388,738,686
Houston,454,1086,430,616,356,534,218,420,494,382,476,846
New Orleans,304,1278,352,598,288,228,532,418,314,496,616,882

到目前为止,这是我的代码:

File selectedFile = Utilities.selectFile("Type the file name: Ex:annualUnitsSold.csv        \n");
int numberRecords = Utilities.countLinesInFile(selectedFile);
String[][] records = Utilities.loadStringsFromFile(selectedFile, numberRecords);

System.out.println(columnCompare(records,1);
public static int columnCompare (String[][] array, int col)
{
    String report = "";
    int monthMax = 0;

    for(int row = 0; row < array.length; row++)
    {
        if(monthMax < Integer.parseInt(array[row][col]))
        {   
            monthMax = Integer.parseInt(array[row][col]);
        }
    }
    return monthMax;
}
//NOTE: when i run this it works as long as i put the column number greater than zero.

2 个答案:

答案 0 :(得分:0)

使用HashMap

HashMap<String, Integer> cities = new HashMap<>();
...
cities.put(city, columnCompare(...));

答案 1 :(得分:0)

您可以查找索引,而不是查找值:

int month = 1;
int store = columnCompare(records, month);
System.out.println(records[store, 0] + ": " + records[store, month]);
public static int columnCompare (String[][] array, int col)
{
    int rowMax = 0;
    int monthMax = -1;
    for(int row = 0; row < array.length; row++)
    {
        int val = Integer.parseInt(array[row][col]);
        if(monthMax < val)
        {
            rowMax = row;
            monthMax = val;
        }
    }
    return rowMax;
}