Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How do a put the contents of case 1 into a method and call it?

See code snippet below:

 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;
 }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
691 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

Invoke with:

showNames(teachers);

Note that the break is not tucked into the function. The function wouldn't have access to the scope of the case statement, and therefore break would do nothing. Make sure break follows your function invocation.

One other thing to point out is the type that I used on the function. I used a Set. Matt Ball used an Iterable. I'm going to leave mine in for the sake of comparison, but using an Iterable is best! The reason is that all Collection types implement the Iterable interface. Inside the function, we are merely iterating over the Set. Therefore, the more general Iterable is the best type choice for the parameter.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...