我很难弄清楚这一点。我应该从提供给我的随机访问文件中读取信息,然后将信息放入几个数组(firstName、lastName、age、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 指的是程序的另一部分,一旦我将信息放入数组,它将类似于我编写的另一个程序