0
我想輸入一個文件,其中包含從一個文件中的幾個人的名字和姓氏到Java程序。我有一個People類,它有兩個字符串用於名和姓,以及用於訪問信息的訪問器和增變器。在我的主要方法裏面,我有一個while循環,它將每個人逐行引入,直到文件結束。假設通過每行的構造函數創建Person的新實例並複製到數組。當while循環結束時,當我打印出數組的內容時,似乎該數組填充了文件中最後一個人的信息。但是,如果我註釋掉String [] values = line.split(「\ t」); Person person = new Person(values [0],values [1]);行並使用二維數組來保存文件中所有信息的副本,那麼它工作正常。有什麼我做錯了,是阻止我保留People數組中文件中包含的所有個人名稱的副本嗎?如何使用特定類的數組?
public class Person
{
protected static String first;
protected static String last;
private static int id;
public Person(String l, String f)
{
last = l;
first = f;
} // end of constructor
public String getFirst()
{
return first;
} // end of getFirst method
public static String getLast()
{
return last;
} // end of getLast method
public static int getID()
{
return id;
} // end of getLast method
public static void setFirst(String name)
{
first = name;
} // end of setFirst method
public static void setLast(String name)
{
last = name;
} // end of setLast method
public static void setID(int num)
{
id = num;
} // end of setLast method
} // end of Person class
public class Driver
{
public static void main(String arg[])
{
Person[] temp = new Person[10];
try
{
BufferedReader br = new BufferedReader(new FileReader(arg[1]));
String line = null;
int counter = 0;
while ((line = br.readLine()) != null)
{
String[] values = line.split("\t");
Person child = new Person(values[0], values[1]);
temp[counter] = child;
System.out.println("Index " + counter + ": Last: " + child.getLast() + " First: " + child.getFirst());
System.out.println("Index " + counter + ": Last: " + temp[counter].getLast() + " First: " + temp[counter].getFirst() + "\n");
counter++;
}
br.close();
}
catch(Exception e)
{
System.out.println("Could not find file");
}
for(int row = 0; row < 7; row++)
{
System.out.print("Row: " + row + " Last: " + temp[row].getLast() + " First: " + temp[row].getFirst() + "\n");
}
}
} // end of Driver class