首页 > 解决方案 > 使用for循环,遍历二维数组以将这些值传递给参数

问题描述

我正在打开一个如下所示的文本文件:

1;Rani;Hockey;BMW;1 Series;2011;WAUGFAFR4CA952133;2003;
2;Ranice;Dodge;Hyundai;Sonata;2005;WAUMF78PX6A683500;2013;

(与上述类似还有 90 行)

我已经将每个单词拆分成一个二维数组,这样位置

[0][0] = 1
[0][1] = Rani
[0][2] = Hockey
[1][0] = 2
[1][1] = Ranice
[1][7] = 2013

我设置了一个 for 循环来遍历我的 2D 数组,其中(最终)每个索引将作为参数传递给我拥有的构造函数。在循环期间,我不断得到:

Exception in thread "main" java.lang.NumberFormatException:
For input string: "2"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at Test4.main(Test4.java:53)

下面是我的 CarData 类的代码:

public CarData() {}

public CarData(int i, String fn, String ln, String cMake, String cMdl, 
                   int cYear, String vin, int p)
{
    this.customerID = i;
    this.ownerFirstName = fn;
    this.ownerLastName = ln;
    this.carMake = cMake;
    this.carModel = cMdl;
    this.carYear = cYear;
    this.carVin = vin;
    this.yearCarPurchased = p;
}

public class CarDataDriver {

public static void main(String [] args)
{
    final int col = 8;
    final int row = 100;
    int id = 0;
    String fn = null;
    String ln = null;
    String cMake = null;
    String cMdl = null;
    int cYear = 0;
    String vin = null;
    int p = 0;
    CarData [] data = new CarData[row];
    // Open file
    File file = new File("CarData.txt");

    // Use scanner to scan new File
    Scanner scanner;
    try {
        scanner = new Scanner(file);

        // useDelimiter to separate String 
        String text = scanner.useDelimiter("\\A").next();

        // Use split method to split String
        String [] array = text.split(";");

        String[][] array2D = new String[row][col];

        //iterate through array to create 2D array
        for (int i = 0, k=0; i < array2D.length; i++)
        { 
            for (int j = 0; j < col; j++)
            {
                array2D[i][j] = array[k++];
            }
        }


        for (int i = 0, k=0; i < array2D.length; i++) 
        {

            for (int j = 0; j < col; j++)
            {
                if(j==0){
                    id = Integer.parseInt(array2D[i][j]); //first iteration where i = 0 runs fine, when i=1 and j=0 I get the error
                    continue;
                }
                if(j==1){
                    fn = array2D[i][j];
                    continue;
                }
                if(j==2)         {                   
                    ln = array2D[i][j];
                    continue;
                }
                if(j==3){
                    cMake = array2D[i][j];
                    continue;
                }
                if(j==4){
                    cMdl = array2D[i][j];
                    continue;
                }
                if(j==5){
                    cYear = Integer.parseInt(array2D[i][j]);
                    continue;
                }
                if(j==6){
                    vin = array2D[i][j];
                    continue;
                }
                if(j==7){
                    p = Integer.parseInt(array2D[i][j]);

                }
                data[k] = new CarData(id, fn, ln, cMake, cMdl, cYear, vin, p);
                k++;
            }

        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

}

标签: javafor-loopmultidimensional-arraymethodsparameters

解决方案


单独的循环很好 - 导致错误的原因是与正确整数一起解析的无效字符(空格)。您可以简单地使用以下命令从字符串中删除所有空格:

array2D[i][j].replaceAll("\\s+","")

(注意,这不会修改数组中的字符串,而是返回删除空格的新字符串)

奇怪"\\s+"的字符串只是意味着“任何空格字符”(它是所谓的正则表达式,但你现在不需要完全理解它)

但是,请注意,您的代码中还有一些问题,例如绝对不必要的内部循环有这么多if的 s,其中每个都只会执行一次 - 而不是这个,您可以简单地访问 array2D[i][1], array2D [i][2] 等等。还保留额外的索引 k 并手动增加它似乎是多余的。

无论如何,继续编码,祝你好运!

PS UsingBufferedReaderreadLine()似乎是一种更好(也更简单!)的读取文件的方法。浏览https://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html


推荐阅读