Home > Software engineering >  How to call a function once for all objects?
How to call a function once for all objects?

Time:12-07

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.

CodePudding user response:

Create a List of attractions as in

List<Attraction> attractions = new ArrayList<>();

Add each attraction to the list:

attractions.add(TheEdenProject);
attractions.add(LondonZoo);
attractions.add(TateModern);

Pass the List to attractionInfo

attractionInfo(attractions);

Define attractionInfo as

// Didn't see why you needed to return Attraction
public static void attractionInfo(List<Attraction> allKnown)

And use it as such:

   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 (allKnown.contains(attraction_name)) {
            Attraction ofInterest = allKnown.get(attraction_name);
            System.out.println(ofInterest.name   " opens at "   ofInterest.open   "am.");
        } else {
            System.out.println("I have no information about that attraction.");
        }
    }

The contains assumes the equals of Attraction is implemented as the desired name comparison. If you need help with that just ask. Or search on [java] equals in SO.

CodePudding user response:

You need some collection to iterate over, like a List.

List<Attraction> attractions = Arrays.asList(
    createAttraction("The Eden Project", 9),
    createAttraction("London Zoo", 10),
    createAttraction("Tate Modern", 10)
);
for (Attraction attraction : attractions) {
    attractionInfo(attraction);
}

Or, more advanced

Stream.of(
    createAttraction("The Eden Project", 9),
    createAttraction("London Zoo", 10),
    createAttraction("Tate Modern", 10)
)
.forEach(attractionGuide::attractionInfo);

CodePudding user response:

The problem is you are calling your loop three times.

    attractionInfo(TheEdenProject);  // This creates a loop
    attractionInfo(LondonZoo);       // Ditto
    attractionInfo(TateModern);      // Ditto

If you want to loop once, you must call the loop only once. Try creating the loop and having it call the method that checks the attraction.

// Closer to main()
    Attraction a;
    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();

        // Add this

        if ( (a = attractionInfo(a.name)) != null ) {
            System.out.println(a.name   " opens at "   a.open   "am.");
        } else {
            System.out.println("I have no information about that attraction.");
        }
    }

CodePudding user response:

Pass an array or collection to iterate over. the simplest change is below, but you could also use a Map to get the info by name rather than iterating over the entire collection .

import java.util.Scanner;


public class AttractionGuide {
    static class Attraction {
        String name;
        int open;

        Attraction(String name, int open) {
            this.name = name;
            this.open = open;
        }
    }

    public static void main(String[] args) {
        attractionDetails();
        System.exit(0);
    }

    public static void attractionDetails() {

        Attraction TheEdenProject = new Attraction("The Eden Project", 9);
        Attraction LondonZoo = new Attraction("London Zoo", 10);
        Attraction TateModern = new Attraction("Tate Modern", 10);

        queryAttractionInfo(TheEdenProject, LondonZoo, TateModern);
    }

    public static void queryAttractionInfo(Attraction ... attractions) {

        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();
            boolean found = false;
            for (Attraction a : attractions) {
                if (attraction_name.equalsIgnoreCase(a.name)) {
                    System.out.println(a.name   " opens at "   a.open   "am.");
                    break;
                }
            }
            if (!found) {
                System.out.println("I have no information about that attraction.");
            }
        }
    }
}

CodePudding user response:

well, there so many answers.
i think this is your mean:

public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        System.out.print("Welcome. Enter attractions count:");
        int count = scanner.nextInt();
        System.out.println("count: "   count);

        attractionInfo(count, "Jim", 10);
        attractionInfo(count, "Tom", 2);
        attractionInfo(count, "Jack", 4);

        scanner.close();
    }

    public static void attractionInfo(int count, String name, int open) {
        for (int i = 1; i <= count; i  ) {
            System.out.print("Enter a name:"); 
            Scanner scanner = new Scanner(System.in);
            String attraction_name = scanner.nextLine();
            if (attraction_name.equalsIgnoreCase(name)) {
                System.out.println( name   " opens at "   open   "am.");
            } else {
                System.out.println("I have no information about that attraction.");
            } 
        } 
        System.out.println("=================");
    }
  • Related