我正在尝试编写一个程序,从文本文件中读取数据,并用它填充Jtable
,我需要能够搜索该表,并使用数字进行一些计算。
文本文件中的一行将包含:
name, country, gender, age, weight
行数未知(我需要计算行数)。 这是我尝试过的,但似乎崩溃了。 我需要计算行数,然后用行中的内容填充数组。
package Jone;
import java.io.*;
import java.util.*;
public class Jone {
public static void main (String [] args)throws IOException{
int rows = 0;
Scanner file = new Scanner (new File("data.txt"));
while (file.hasNextLine()){rows++;}
Object[][] data = new Object[rows][5];
System.out.print(rows);
file.nextLine();
for(int i = 0;i<rows;i++)
{
String str = file.nextLine();
String[] tokens= str.split(",");
for (int j = 0;j<5;j++)
{
data[i][j] = tokens[j];
System.out.print(data[i][j]);
System.out.print(" ");
}
}
file.close();
}
}
最佳答案
按如下方式更改代码
package Jone;
import java.io.*;
import java.util.*;
public class Jone {
public static void main (String [] args)throws IOException{
try{
int rows = 0;
Scanner file = new Scanner (new File("data.txt"));
while (file.hasNextLine())
{
rows++;
file.nextLine();
}
file = new Scanner (new File("data.txt"));
System.out.println(rows);
Object[][] data = new Object[rows][5];
for(int i = 0;i<rows;i++)
{
String str = file.nextLine();
String[] tokens= str.split(",");
for (int j = 0;j<5;j++)
{
data[i][j] = tokens[j];
System.out.print(data[i][j]);
System.out.print(" ");
}
}
file.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
关于JAVA从文件中填充未知行数的二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20677391/