繁体   English   中英

将从文本文件读取的字符串拆分为2D字符数组

[英]Splitting strings read from text file as a 2d array of characters

我必须在代码中使用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

您在输出数据时遇到问题。

尝试

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

我认为,如果您看一下这段代码,您会发现您的循环是错误的。

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 <z如果q和z都从0开始,则q从开始处不小于z,它等于z,并且当循环完成并且q增加时,它现在大于z。 也许正在改变不平等。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM