如何将案例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;
}
答案 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;