呼叫&在不同的班级中搜索Arraylist

时间:2013-05-07 06:03:44

标签: java class collections iterator

我正在构建一个程序来读取.txt文件并提取学生数据并将其存储在一个集合中。然后,用户应该能够选择几个不同的查询。我要求帮助的查询是选择所有毕业的学生,​​例如,2014年,然后将这些结果打印到屏幕上。

简而言之,如何为2014年毕业的学生搜索存储在ProcessRecords课程中的Arralist?我只是不明白如何从另一个班级打电话。

以下是我的代码:

头等舱:使用主要方法

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");
        Query query = new Query(studentRecords);
        int searchType=preference.nextInt();
        //How would I throw an exception here if the user doesn't enter a number or enters a number less than 1 or great than 4
        //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
            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
            //Also 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
 {
private int id;
private String last;
private String first;
private int year;

public StudentRecord(int id, String last, String first, int year)
{
    this.id=id;
    this.last=last;
    this.first=first;
    this.year=year;
}

public String toString()
{
    return id + "  " + last + "  " + first + "  " + year;
} 

public int getYear()
{

    return year;
}
}


三等(我要求帮助的那个)

 import java.util.*;
 import java.io.*;

  public class Query
 {
    //public static ProcessRecords studentrecord = new ProcessRecords();
     private List<StudentRecord> records;

     public Query(List<StudentRecord> records) {
         this.records = records;
    }

    public int getYear(int yearSearch) {
    int count = 0;

         for(StudentRecord record : records) {
             if(record.getYear() == yearSearch) {
                 count++;
             }
        }

       return count;
  }
  }

添加了新帖子!

4 个答案:

答案 0 :(得分:0)

你必须让studentRecords成为静态变量或实例变量,

这样说,主要在:

public static List<StudentRecord> studentRecords ;
public static void main(String[] args)
throws Exception{

studentRecords = new ArrayList<StudentRecord>();

然后就这样称呼它:

ProcessRecords.studentRecords

答案 1 :(得分:0)

您的代码存在多个问题。

  1. 不建议使用公共变量,应使用getter / setter来访问对象成员。 Eclipse alt+s, r将为您生成

  2. 您的变量名称具有误导性。您在Query中访问的列表是什么?

  3. 您的课程名称也(至少!)具有误导性。 ProcessRecords特别是行动似乎很糟糕。在这种情况下,该类不应该是名词,如RecordsProcessor吗?它不应该暗示它实际上在做什么吗? StudentYearSearcher

  4. 您不会抛出列表,将它(它的引用)作为参数传递,或以某种方式访问​​它。你抛出例外

  5. 回答您的问题

    有多种方法可以做到。一种方法是使用单例模式并使列表静态可访问。像这样:

    class StudentRecord {
      static List<StudentRecord> studentRecords;
    
      List<StudentRecord> getStudentRecords() {
        if (studentRecords == null) studentRecords= new ArrayList<StudentRecord>();
        return studentRecords;
      }
    
      //the reest of the class
    }
    

答案 2 :(得分:0)

最简单的解决方案是将整个列表传递给getYear方法:

public static int getYear(List<StudentRecord> studentRecords, int yearsearch) {
      // ProcessRecords processRecords = new ProcessRecords();  <- don't need it
      int getYear= yearsearch;
      Iterator itr = studentRecords.iterator();

      // ...

答案 3 :(得分:0)

让您的Query类看起来像这样:

public class Query {

    private List<StudentRecord> records;

    public Query(List<StudentRecord> records) {
        this.records = records;
    }

    public int getYear(int yearSearch) {
       int count = 0;

       for(StudentRecord record : records) {
           if(record.getYear() == yearSearch) {
               count++;
           }
       }

       return count;
    }

    public int otherQuery() {
        // code for another query
    }
}

然后在你的主要课程中:

import java.util.*;
import java.io.*;
import java.lang.*;

public class ProcessRecords {

    public static void AskUser(Query query) throws Exception {
        // all the code you have right now except the line where you
        // create a new Query object   
    }

    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());
        }

        Query query = new Query(studentRecords); // we've moved this out of AskUser method to here

        // now we call the AskUser method and pass it this query object we just
        // created so it can have access to it, meaning inside the AskUser method we can
        // say things like 'query.getYear(2014);'

        AskUser(query);
    }
}