我想讀取一個txt文件並將文件中的每條記錄存儲到名爲data []的對象數組中。除了記錄部分沒有在數據[]中正確分配以外,一切正常。找不到爲什麼數組顯示爲null
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;
}
}
使用eclipse來調試你的代碼 - 在第1行設置一個斷點並逐行檢查每個變量。你會很快發現問題。 – Bohemian