我正在編寫一個程序,它將讀取一個文件併爲每個學生提取數據。我用while循環和input.next()成功完成了這個任務。但是,我需要將變量傳遞到一個集合中以記錄每個學生的數據,因此對於每個循環,我想再次將4個變量(id,first,last,year)添加到集合中。我應該注意的是,收藏必須放在不同的班級,我必須能夠搜索這個收藏,例如找到今年畢業的所有學生。 如果任何人都可以直接指出我關於將變量存儲在每個循環的不同類中的集合中。 我知道這是一個基本問題,但我對Java非常陌生,所以我很感謝大家的幫助!版本2.0(現在添加查詢)
第一類是
import java.util.*;
import java.io.*;
import java.lang.*;
public class ProcessRecords {
public static void AskUser()
throws Exception {
Scanner preference = new Scanner(System.in);
//Creating a new scanner will allow us to gather user input
boolean flag=true;
//I will use this for my while loop
while (flag) {
System.out.println("What type of Search would you like to run?\n 1)Search for all students\n 2) Search for students graduating in a specific year\n 3)Search for students whose last name begins with a certain string\n");
int searchType=preference.nextInt();
//This variable will store what type of query the user would like to run
switch(searchType) {
case 1:
System.out.println("Gathering Records for all students\n");
//Call Query Method in the Query Class to return all students in the colletion
case 2
System.out.println("What graduation year would you like to search for? \n");
String yearsearch=preference.next();
//Call Query Method to return students who are graduating in the specified year
//Pass the "yearsearch" variable to the Query class to run the search
case 3:
System.out.println("What string would you like to search for? \n");
String lstsearch=preference.next();
//Call Query Method in the Query Class to return students who have the string in their last name
//I need to pass the "lstsearch" variable to the Query class to search through last names
}
}
}
public static void main(String[] args)
throws Exception
{
Scanner input = new Scanner(new File("students.txt"));
//This will import the file
input.nextLine();
//This will skip the headers in the file
System.out.println("Processing file now...");
//Let the user know that the file is being processed
int id;
String last;
String first;
int year;
int i=1;
// Declare variables that we will extract from the file
//Now we will being processing the file with a while loop
List<StudentRecord> studentRecords = new ArrayList<StudentRecord>();
while(input.hasNext())
{
id=input.nextInt();
last=input.next();
first=input.next();
year=input.nextInt();
StudentRecord record = new StudentRecord(id, last, first, year);
studentRecords.add(record);
System.out.println(id + " " + last + " " + first + " " + year + "\n");
}
System.out.println(" You have successfully read and printed from the file!");
for (StudentRecord s : studentRecords)
System.out.println(s.toString());
}
}
下一班是
public class StudentRecord{
public int id;
public String last;
public String first;
public int year;
public StudentRecord(int d, String lt, String ft, int yr){
id=d;
last=lt;
first=ft;
year=yr;
}
public String toString()
{
return id + " " + last + " " + first + " " + year;
}
}
謝謝!
我會建議你創建一個類的屬性你需要存儲 – Barranka 2013-05-06 23:44:42