抱歉,如果我的代码看起来很糟糕,我在编程方面没有那么丰富的经验。我需要以以下格式从 .txt 传输文本:日期-名称-地址等..
我正在读取文件,然后使用 String.split("-") 分割字符串。我在循环方面遇到了麻烦。
try{
File file = new File("testwrite.txt");
Scanner scan = new Scanner(file);
String[] test = scan.nextLine().split("-");
while(r<100){
while(c<6){
data[r][c] = test[c];
test = scan.nextLine().split("-");
c++;
}
r++;
c = 0 ;
}
System.out.println(data[1][5]);
}catch(Exception e){
System.out.println("Error: " + e.getMessage());
}
最佳答案
二维数组只是“数组的数组”,因此可以直接使用split
结果来存储一行数据。
File file = new File("testwrite.txt");
Scanner scanner = new Scanner(file);
final int maxLines = 100;
String[][] resultArray = new String[maxLines][];
int linesCounter = 0;
while (scanner.hasNextLine() && linesCounter < maxLines) {
resultArray[linesCounter] = scanner.nextLine().split("-");
linesCounter++;
}
关于java - 从 .txt 读入二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13500432/