用Java创建方法

时间:2011-12-04 14:18:31

标签: java

如何将案例1的内容放入方法并调用它?

请参阅下面的代码段:

 Teacher jane = new Teacher("jane");
 Teacher alex = new Teacher("alex");

 Set<Teacher> teachers = new HashSet<Teacher>();
 teachers.add(jane);
 teachers.add(alex);

 int selection = scan.nextInt();
 switch (selection) {
     case 1:
         for (Teacher teacher : teachers) {
             System.out.printf("%s ", teacher.getName());
         }
         break;
 }

3 个答案:

答案 0 :(得分:4)

private void showNames(Set<Teacher> teachers) {
    for (Teacher teacher : teachers) {
        System.out.printf("%s ", teacher.getName());
    }
}

调用:

showNames(teachers);

请注意,break不会隐藏在函数中。该函数无法访问case语句的范围,因此break将不执行任何操作。确保break跟随您的函数调用。

另外要指出的是我在函数上使用的类型。我使用了Set。 Matt Ball使用了Iterable。为了比较,我打算离开我,但使用Iterable是最好的!原因是所有Collection类型都实现了Iterable接口。在函数内部,我们只是迭代Set。因此,更通用的Iterable是参数的最佳类型选择。

答案 1 :(得分:3)

声明:

void printNames(Iterable<Teacher> teachers) {
    for (Teacher teacher : teachers) {
        System.out.printf("%s ", teacher.getName());
    }
}

用法:

switch (selection) {
     case 1:
         printNames(teachers);
         break;

答案 2 :(得分:2)

方法:

public void printTeachers(set<Teacher> teachers){
  for (Teacher teacher : teachers) {
    System.out.printf("%s ", teacher.getName());
  }
}

其他代码:

Teacher jane = new Teacher("jane");
Teacher alex = new Teacher("alex");

Set<Teacher> teachers = new HashSet<Teacher>();
teachers.add(jane);
teachers.add(alex);

int selection = scan.nextInt();
switch (selection) {
    case 1:
        printTeachers(teachers);
        break;