首页 > 解决方案 > 将类变量传递给java中另一个类的方法

问题描述

我刚刚开始学习 java renow 。我创建了一个包含变量 ID 和名称的班级学生和另一个班级学生列表,它是学生的数组列表。

我想创建允许传递 variale 的特技类名称(ID 或名称)和变量值的 seach 函数。我该怎么做 ?

class Student{
    String ID;
    String name;

    public Student(){

    }

    public Student(String ID,String name){
        this.ID =  ID;
        this.name = name;
    }

    public String getStudent() {
        String info = this.ID +"\t\t\t"+ this.name;
        return info;
   }
}


class StudentList{

    private ArrayList <Student> list = new ArrayList<>();
    private int counter = 0;
    static Scanner sc = new Scanner(System.in);

    public StudentList(){
    
    }

    public StudentList(Student stu){
        Student student = new Student(stu.ID,stu.name);
        this.list.add(student);
        this.counter++;
    }
    public int seach(String type(name or ID) , String value ){
        int i;
        int found = 0;
        for(i = 0; i < list.size();i++){

            if(value.equals(list.get(i).type){
                found++;
                System.out.println(value.equals(list.get(i).type);
            }
        }

        return found;
    }
}

标签: javaclassvariablesmethods

解决方案


首先,我建议将您的Student类的属性设置为私有。然后你可以添加setter和getter。

public class Student {
   private String ID;
   private String name;

   public Student() {}

   public Student(String ID, String name) {
     this.ID = ID;
     this.name = name;
   }

   public String getID() { return ID; }
   public String getName() { return name;
   public void setID(String ID) { this.ID = ID; }
   public void setName(String name) { this.name = name; }
}

在您的课程StudentList中,我将拆分和扩展搜索的功能,而不是将值类型作为附加参数传递。

public class StudentList {
      ...
      public int searchByName(String name) {
         for(int i=0; i < list.size(); i++) {
            if(list.get(i).getName().equals(name)) return i;
         }
         
         return -1;
      }

      public int searchByID(String ID) {    
         for(int i=0; i < list.size(); i++) {
            if(list.get(i).getID().equals(ID)) return i;
         }
         
         return -1;
      }

      public int searchStudent(Student stud) { return list.indexOf(stud); }
}

如果您确实需要一个捆绑所有这些功能的函数,您可以添加另一个函数,该函数通过一个标志决定应该使用传递的参数调用哪个函数。您还可以在此处添加对参数的检查,同时具有更大的灵活性和职责分离。

public int search(int flag, arg Object) {
    if(flag == 0) return searchStudent((Student) arg);
    else if(flag == 1) return searchByID((String) arg);
    else return searchByName((String) arg);
}

附加说明:如果您想用变量指示列表中的当前学生人数counter,我强烈建议您删除此变量,并size()在需要时始终调用列表的方法。每个 Java 集合(即 ArrayList)都提供它,并且在删除或添加学生后它总是会返回正确的值。为此任务实现您自己的计数器将导致更容易出错的源代码。


推荐阅读