我在解決這個問題時遇到了一些麻煩。我應該從提供給我的隨機訪問文件中讀取信息,然後將這些信息放入幾個數組中(名字,姓氏,年齡,gpa,computerClub)。我被告知什麼類型的信息被寫入,但不是以什麼順序。我如何讀取這些信息並將其放入適當的數組中。這是我到目前爲止:我將如何從隨機訪問文件中獲取信息並將其放入多個數組中?
import java.io.*;//imports the IO tools for use in this program
import java.text.DecimalFormat;//imports the decimal format tool for use in this program
public class RandomAccessProject
{
public static void main(String[] args)throws Exception
{
String[] firstName = new String[100];//creates an array of length 100 called firstName
String[] lastName = new String[100];//creates an array of length 100 called lastName
int[] age = new int[100];//creates an array of length 100 called age
double[] gpa = new double[100];//creates an array of length 100 called gpa
boolean[] computerClub = new boolean[100];//creates an array of length 100 called computerClub
int numElements = loadArrays(firstName,lastName,gpa,age,computerClub);//invokes the loadArrays method to fill the created arrays with values from the text file.
printArrays(firstName,lastName,gpa,age,computerClub,numElements);
}
/*
* loadArrays
* @param String[] first ,String[] last,double[] grades, int[] age, boolean[] club.
* @return int count
*/
public static int loadArrays(String[] first, String[] last, double[] grades,int[] age, boolean[] club) throws Exception
{
RandomAccessFile inputFile = new RandomAccessFile("rand.dat","r");//creates a new File object
int count = 0;//creates and initializes a variable for dermining which element of an array is interacted with
int r = 0;
while((r = inputFile.read()) != -1)
{
String firstName = inputFile.readUTF();//takes the next string and places it into the firstName variable
String lastName = inputFile.readUTF();//takes the next string and places it into the lastName variable
int old = inputFile.readInt();
double gpa = inputFile.readDouble();//takes the next double and places it into the score variable
boolean compClub = inputFile.readBoolean();
first[count] = firstName;//sets the element corresponding to the current value of count in the first array to the firstName array
last[count] = lastName;//sets the element corresponding to the current value of count in the last array to the lastName array
age[count] = old;
grades[count] = gpa;//sets the element corresponding to the current value of count in the first array to the score array
club[count] = compClub;
count++;//increment count by one
}
return count;
}
這會產生EOFException,我不知道還有什麼可以工作。 注意:count和printArrays指的是程序的另一部分,其操作與編寫另一個程序類似,一旦我將信息讀入陣列中
爲此,已指定它不會超過100個元素。 我不知道如何將文件作爲一個.dat文件,而不是文本佈局。 對於本書,課堂或任何演示文稿中未指定的內容,它只是很難找到解決方案。 – Iccirrus
打開記事本或類似文件中的.dat文件(即使它不是.txt,它仍會讀取它,如果它的文本數據顯示它)。 –