gpt4 book ai didi

JAVA从文件中填充未知行数的二维数组

转载 作者:太空宇宙 更新时间:2023-11-04 07:10:42 27 4
gpt4 key购买 nike

我正在尝试编写一个程序,从文本文件中读取数据,并用它填充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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com