我想读取一个txt文件并将文件中的每条记录存储到一个名为data []的对象数组中。除了在数据[]中没有正确分配记录部分外,一切正常。
This is the format for the record.txt...
4252 4 item1
2435 23 item2
4355 16 item3
so on and so on...
我想继续使用我一直在使用的方法,即使有更简单的方法(总是存在)。
非常感谢...
import java.util.Scanner;
import java.io.*;
public class SortsTest
{
private static Data[] data;
private static String file_to_read;
private static int num_of_records,
current_record = 0;
private final static int RECORD_DATA = 3;
private static Scanner scan_file1;
public static void main(String[] args) throws IOException
{
try {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a file name: ");
file_to_read = scan.next();
System.out.print("\nInput file = " + file_to_read);
System.out.print("\n# of records = ");
num_of_records = scan.nextInt();
scan_file1 = new Scanner(new File(file_to_read));
//---------------------- populate data array ------------------------
while (scan_file1.hasNext())
{
data = new Data[num_of_records];
String record[] = new String[RECORD_DATA];
for(int i = 0; i < RECORD_DATA; i++)
{
String line = scan_file1.next();
record[i] = line;
}
data[current_record] = new Data(record[0],record[1], record[2]);
current_record++;
}
//--------------------------------------------------------------------
//System.out.print("\n\nRecord 10: " + data[10].getPartName() + " " + data[10].getQuantity() + " " + data[10].getPartNumber());
System.out.print("\n\nRecord 10: " + data[10]);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
///////////////////////////// Data file /////////////////////////////////
import java.util.Scanner;
import java.io.*;
public class Data
{
private int part_num,
quantity;
private String part_name;
private Scanner scan_file1;
public Data(String part, String quan, String name)
{
part_num = Integer.parseInt(part);
quantity = Integer.parseInt(quan);
part_name = name;
}
public void setPartNumber(int num)
{
part_num = num;
}
public void setQuantity(int quan)
{
quantity = quan;
}
public void setPartName(String name)
{
part_name = name;
}
public int getPartNumber()
{
return part_num;
}
public int getQuantity()
{
return quantity;
}
public String getPartName()
{
return part_name;
}
}
答案 0 :(得分:2)
通过while循环每次迭代都会创建一个新的空数据数组,请尝试:
data = new Data[num_of_records];
while (scan_file1.hasNext())
{
答案 1 :(得分:1)
如果不深入您的代码,我怀疑这是您的问题的一部分:
//---------------------- populate data array ------------------------
while (scan_file1.hasNext())
{
// you recreate your array every loop iteration
data = new Data[num_of_records];
相反,您需要执行以下操作:
//---------------------- populate data array ------------------------
data = new Data[num_of_records];
while (scan_file1.hasNext())
{