拆分字符串从文本文件读取为2d字符数组

时间:2013-02-01 13:10:22

标签: java arrays iteration

我必须在我的代码中使用2d数组,我在将字符串拆分为1d数组并将其存储在我的2d数组testCases[][]中的位置时遇到了很多麻烦。我在从文本文件中读取字符串后使用split函数来创建一个字符数组。我的代码中的所有内容似乎都对我有意义,但是,当我尝试迭代并打印出testCases数组以确保我收集了正确的数据时,它会打印出不正确的数据。

我很感激帮助解决这个问题,我花了好几个小时来处理这个问题。

非常感谢提前。

//Read number of test cases 
String x = fin.nextLine();
int numTests = Integer.parseInt(x);

//create array
testCases = new String[numTests][100];

//Read actual test cases and store in 2d array
for(int i = 0; i < numTests; i++){
    String testCaseString = fin.nextLine();

    //System.out.println(testCaseString);                   
    testCases[i] = testCaseString.split("(?!^)"); 
    System.out.println(testCases[i][0]);
}
for(int z=0; z < numTests; z++){
    for(int q=0; q  < z; q++){
        System.out.printf("%s ", testCases[z][q]);
    }
    System.out.println();
}

测试用例 - 文本文件位置

2
bcb
c

当前控制台输出

c

所需的控制台输出

b c b
c

2 个答案:

答案 0 :(得分:1)

输出数据时遇到问题

尝试

for(int z=0; z < numTests; z++){
    for(int q=0; q  < testCases[z].length; q++){
        System.out.printf("%s ", testCases[z][q]);
    }
    System.out.println();
}

在内循环中,你应该迭代到testCases[z].length

答案 1 :(得分:0)

我认为如果你看一下这段代码,你会发现你的循环有问题。

for(int z=0; z < numTests; z++){
    for(int q=0; q  < z; q++){
        System.out.printf("%s ", testCases[z][q]);
    }
    System.out.println();
}

q&lt; z如果q和z都从0开始,那么从开始q开始不小于z,它等于z,当循环完成并且q递增时,它现在大于z。也许改变不平等。

相关问题