IndexOutOfBoundsException?从txt文件读取并创建2D数组

时间:2019-11-16 16:14:20

标签: java arrays matrix multidimensional-array

过去5-8个小时,我一直在努力解决这项任务,但无济于事。 我被分配阅读一个txt文件,该文件包含约50行的“ carModel,carColor”,并创建一个[8] x [8] 2d数组,该数组的每个汽车模型都位于矩阵顶部,每个汽车颜色都位于矩阵顶部。二维矩阵的左侧,均已排序。然后,每次选择某些“ carModel,carColor”时,它们各自的carModel和carColor都会更新1。就像汽车库存表一样。

我已经从两个单独的ArrayList创建了一个String的2D数组,并填充了应该为所有零的空空间,即字符串“ 0”。但是现在我在读取文件时遇到了麻烦,因此每次选择特定的“ carModel,carColor”时,它都会更新原始的[8] x [8]字符串数组。我在哪里错了,我该怎么做才能使此操作更容易/更有条理?

这是我当前整个作业的代码:

public class Cars1 {
public static void main (String [] args) throws Exception
{
    String [][] cars = new String [8][8]; 
    ArrayList <String> colors = new ArrayList<>();
    colors.add("BLUE  ");
    colors.add("BLACK ");
    colors.add("BROWN ");
    colors.add("GREEN ");
    colors.add("RED   ");
    colors.add("SILVER");
    colors.add("WHITE ");
    Collections.sort(colors);
    ArrayList <String> models = new ArrayList<>();
    models.add("Escape  ");
    models.add("Explorer");
    models.add("F150    ");
    models.add("F250    ");
    models.add("Flex    ");
    models.add("Mustang ");
    models.add("Taurus  ");
    Collections.sort(models);
    cars [0][0] = "_____  ";
    for (int a = 1; a < cars.length; a++)
    {
        cars[0][a] = (models.get(a-1)) + " ";
    }
    for (int b = 1; b < cars.length; b++)
    {
        cars[b][0] = (colors.get(b-1)) + " ";
    }
    for (int fir = 1; fir < cars.length; fir++)
    {
        for (int sec = 1; sec < cars[1].length; sec++)
        {
            if (cars[fir][sec] == null)
            {
                cars[fir][sec] = "0        ";
            }
        }
    }       
    for (int first = 0; first < cars.length; first++)
    {
        for (int second = 0; second < cars[first].length; second++)
        {
            System.out.print(cars[first][second]);
        }
        System.out.println();
    }        
    File file = new File ("/Users/blakells/NetBeansProjects/Examples/cars.txt");
    Scanner sc = new Scanner(file);
    String ab = sc.nextLine();
    int[][]count = new int [8][8];
       while (ab != null) 
       {

   String model = ab.substring(0,ab.indexOf(",")).toLowerCase();
   // I get the exception here
   String color = ab.substring(ab.indexOf((",")+1)).toLowerCase();
   int row = colors.indexOf(color.toLowerCase());
   int col = models.indexOf(model.toLowerCase());
   count[row][col]++;        
}
}
}

0 个答案:

没有答案