1 回答

TA貢獻1817條經(jīng)驗 獲得超14個贊
您可以在 while 循環(huán)之前創(chuàng)建兩個數(shù)組,然后將循環(huán)內(nèi)的每個元素添加到每個數(shù)組中。但這種方法有一個問題:我們不知道值的數(shù)量,因此我們無法為此創(chuàng)建固定大小的數(shù)組。我建議改為使用ArrayList,它可以根據(jù)需要增長。像這樣的東西:
public static void main(String[] args) throws FileNotFoundException {
Scanner gpadata = new Scanner(new File("studentdata.txt"));
List<String> IDs = new ArrayList<>();
List<Double> GPAs = new ArrayList<>();
while (gpadata.hasNext()) // loop until you reach the end of the file
{
String snum = gpadata.next(); // reads the student's id number
double gpa = gpadata.nextDouble(); // read the student's gpa
IDs.add(snum);
GPAs.add(gpa);
System.out.println(snum + "\t" + gpa); // display the line from the file in the Output window
}
// Use IDs and GPAs Lists for other calculations
}
更好的方法是使用MapGPA 與學(xué)生 ID“配對”。
編輯:
在您澄清最大記錄數(shù)永遠不會超過 1000 后,我修改了我的解決方案以使用數(shù)組而不是列表。我沒有更改變量名稱,因此您可以輕松比較解決方案。
public static void main(String[] args) throws FileNotFoundException {
Scanner gpadata = new Scanner(new File("studentdata.txt"));
String[] IDs = new String[1000];
double[] GPAs = new double[1000];
int counter = 0;
while (gpadata.hasNext()) // loop until you reach the end of the file
{
String snum = gpadata.next(); // reads the student's id number
double gpa = gpadata.nextDouble(); // read the student's gpa
IDs[counter] = snum;
GPAs[counter] = gpa;
System.out.println(snum + "\t" + gpa); // display the line from the file in the Output window
counter++;
}
// Use IDs and GPAs Lists for other calculations
}
請注意,我們需要一個counter(又名索引)變量來尋址數(shù)組槽。
添加回答
舉報