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

Categories

0 votes
685 views
in Technique[技术] by (71.8m points)

Creating a method in Java

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

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

1 Answer

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...