I'm having trouble understanding how I can call a function with multiple objects only once (within a for loop).
I'm trying to write a code where information of the objects should be passed to another function.
Take the following program for example where, instead of once, the function is being called multiple times.
import java.util.Scanner;
class Attraction {
String name;
int open;
}
public class attractionGuide {
public static void main(String[] args) {
attractionDetails();
System.exit(0);
}
public static Attraction createAttraction(String attractionName, int openingTime) {
Attraction a = new Attraction();
a.name = attractionName;
a.open = openingTime;
return a;
}
public static void attractionDetails() {
Attraction TheEdenProject = createAttraction("The Eden Project", 9);
Attraction LondonZoo = createAttraction("London Zoo", 10);
Attraction TateModern = createAttraction("Tate Modern", 10);
attractionInfo(TheEdenProject);
attractionInfo(LondonZoo);
attractionInfo(TateModern);
// This is where the problem is^
}
public static Attraction attractionInfo(Attraction a) {
Scanner scanner1 = new Scanner(System.in);
System.out.print("Welcome. How many attractions do you need to know about? ");
final int howMany = scanner1.nextInt();
for (int i = 1; i <= howMany; i++) {
System.out.print("\nName of attraction number number " + i + "?: ");
Scanner scanner2 = new Scanner(System.in);
String attraction_name = scanner2.nextLine();
if (attraction_name.equalsIgnoreCase(a.name)) {
System.out.println(a.name + " opens at " + a.open + "am.");
} else {
System.out.println("I have no information about that attraction.");
}
}
return a;
}
}
Example output:
Welcome. How many attractions do you need to know about? 3
Name of attraction number number 1?: the eden project
The Eden Project opens at 9am.
Name of attraction number number 2?: tate modern
I have no information about that attraction.
Name of attraction number number 3?: london zoo
I have no information about that attraction.
Welcome. How many attractions do you need to know about?
It seems since the function is being called three times within the loop, it will only take one argument at a time, whereas the desired output should look something like this:
Expected output:
Welcome. How many attractions do you need to know about? 3
Name of attraction number number 1?: the eden project
The Eden Project opens at 9am.
Name of attraction number number 2?: tate modern
Tate Modern opens at 10am.
Name of attraction number number 3?: london zoo
London Zoo opens at 10am.
so how do I go about calling the function once so it takes all the arguments at once? Any help is appreciated. Thanks.