Gianna Caruso
Gianna Caruso

Reputation: 113

How to make a method that searches a parallel array?

I have written a working parallel array list that stores 12 countries and their corresponding populations. I am having some trouble with second piece of my assignment. I have to create a method that searches the array for the country/population that the user inputs. (For example, if the user inputs "United Kingdom", then it's corresponding population would print). However, I'm not sure how to tackle this. Any tips and advice would be greatly appreciated!

import java.util.Scanner;

public class InClassModule12
   {
      public static void main(String[] args)
      {
     String[] country = {"United States", "Brazil", "China", "Italy", "United Kingdom", "Spain", "Japan", "Germany", "France", "Turkey", "South Africa", "Argentina"};
     int[] population = { 319111000, 203462000, 1367960000, 60783711, 64105654, 46507760, 127090000, 80767000, 66050000, 76667864, 54002000, 42669500};

     for ( int i = 0; i < country.length; i++ )
     { 
       System.out.print( country[i]+ "'s population: " + " ");
        System.out.print( population[i] );
        System.out.println();
     }

  }
}

Edited: This is the exact assignment: In a program you need to store the populations of 12 countries. Define two arrays that may be used in parallel to store the names of the countries and their populations. Write a loop that uses these arrays to print each country's name and its population. Add a loop in your main method which asks the user running it if they would like to look up a given country's population. When they indicate “No” the program terminates. Prompt user: What country would you like to look up? Upon user entering something the program calls the countryLookup method. countryLookup method accepts an argument (parameter) containing what the user entered for the country to look up. The method searches country name array for the name and upon finding it returns the corresponding population from the population array. If it doesn't find the country simply return -1.

Upvotes: 0

Views: 4028

Answers (4)

Lajos Arpad
Lajos Arpad

Reputation: 76892

Try out this untested code, where I have declared the arrays as members, implemented the method and called the method from main. Also, please, make sure you are tabulating your code better in the future:

import java.util.Scanner;

public class InClassModule12 {
    public static String[] country = {"United States", "Brazil", "China", "Italy", "United Kingdom", "Spain", "Japan", "Germany", "France", "Turkey", "South Africa", "Argentina"};
    public static int[] population = { 319111000, 203462000, 1367960000, 60783711, 64105654, 46507760, 127090000, 80767000, 66050000, 76667864, 54002000, 42669500};

    public static String searchPopulation(String c) {
        for (int i = 0; i < country.length; i++) {
            if (country[i].equals(c)) {
                return population[i];
            }
        }
        return "Not found";
    }

    public static void main(String[] args)
    {

        for ( int i = 0; i < country.length; i++ ) { 
            System.out.print( country[i]+ "'s population: " + " ");
            System.out.print( population[i] );
            System.out.println();
        }
        System.out.println(searchPopulation((new Scanner(System.in)).nextLine()));

    }
}

Upvotes: 1

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79876

I have two thoughts to share with regard to this question. The first is that it's screaming out to be programmed in an object-oriented way. That is, there's a little collection of data, and some methods that will operate on that data. So it makes sense to have a class whose objects actually contain that data, and whose methods do the processing; as opposed to, for example, a program where everything is static and nothing ever gets instantiated. The main method can then look after the interactions with the user. And although you CAN put main into the class that stores the data, it makes a good deal of sense not to.

My second thought is that for actually searching the array, it makes sense to use the Apache commons ArrayUtils class, which has the method indexOf, which is perfect for this use case. However, I've presented an alternative in case Gianna's teacher has some objection to the use of external libraries. Honestly, I feel that one of the key differences between an excellent Java programmer and a mediocre Java programmer is knowledge of what classes are readily available, for performing certain common tasks.

Anyway, the class that stores the data could look like this.

import org.apache.commons.lang3.ArrayUtils;

public class PopulationLookup {
    private String[] countries;
    private int[] populations;

    public PopulationLookup(String[] countries, int[] populations) {
        this.countries = countries;
        this.populations = populations;
    }

    public void printAll() {
        for (int i = 0; i < countries.length; i++) {
            System.out.format(
                "Country: %s, population %d%n", countries[i], populations[i]);
        }
    }

    public int populationForCountry(String country) {
        int entry = ArrayUtils.indexOf(countries, country);
        if (entry != -1) {
            return populations[entry];
        } else {
            return -1;
        }
    }
}

This isn't perfect. There's no error handling around what should happen if the two arrays are not the same size, or if one of them is null, or a few other things that can go wrong. Also, ideally, you'd copy all the array entries, rather than just references to the arrays themselves, in case the class that calls this one then starts modifying the entries of the arrays. Those are good changes to make in version 2.

But this class demonstrates how to wrap your data up in an object, how to pass in the data via a constructor, and of course, the searching is there.

You'll need to add Apache commons lang3 to the build path to get this to work. This is documented here and the JAR is available from here. If you really don't want to use an external library, you could change the populationForCountry method like this.

    public int populationForCountry(String country) {
        for (int i = 0; i < countries.length; i++) {
            if (countries[i].equals(country)) {
                return populations[i];
            }
        }
        return -1;
    }

Then, to complete the assignment, you need the class that contains main, to call this. The important point to notice is the instantiation of the PopulationLookup class, passing the data that you were provided with.

import java.util.Scanner;

public class InClassModule12 {
    public static void main(String[] args)
    {
        String[] countries = {
                "United States", "Brazil", "China", "Italy", "United Kingdom", "Spain",
                "Japan", "Germany", "France", "Turkey", "South Africa", "Argentina"};
        int[] populations = {
                319111000, 203462000, 1367960000, 60783711, 64105654, 46507760, 
                127090000, 80767000, 66050000, 76667864, 54002000, 42669500};
        try( Scanner input = new Scanner(System.in)) {

            PopulationLookup lookup = new PopulationLookup(countries, populations); 

            lookup.printAll();
            while(true) {
                System.out.println("Would you like to look up a country?");
                String response = input.nextLine();
                if (response.equalsIgnoreCase("no")) {
                    System.out.println("Good bye");
                    break;
                }

                System.out.println("What country would you like to look up?");
                String country = input.nextLine();
                int population = lookup.populationForCountry(country);
                System.out.format("The population of %s is %d%n", country, population);
            }
        }
    }
}

Edit

This code uses the "try with resources" feature to ensure that the Scanner is closed at the end. This was introduced in Java 7. If you are using an earlier version of Java, then it is best to use a finally block to close the Scanner. That would look like this. The Java 7 code above is basically a shorter way of writing the same thing.

public class InClassModule12 {
    public static void main(String[] args)
    {
        String[] countries = {
                "United States", "Brazil", "China", "Italy", "United Kingdom", "Spain",
                "Japan", "Germany", "France", "Turkey", "South Africa", "Argentina"};
        int[] populations = {
                319111000, 203462000, 1367960000, 60783711, 64105654, 46507760, 
                127090000, 80767000, 66050000, 76667864, 54002000, 42669500};

        Scanner input = new Scanner(System.in);
        try {
            PopulationLookup lookup = new PopulationLookup(countries, populations); 

            lookup.printAll();
            while(true) {
                System.out.println("Would you like to look up a country?");
                String response = input.nextLine();
                if (response.equalsIgnoreCase("no")) {
                    System.out.println("Good bye");
                    break;
                }

                System.out.println("What country would you like to look up?");
                String country = input.nextLine();
                int population = lookup.populationForCountry(country);
                System.out.format("The population of %s is %d%n", country, population);
            }
        } finally {
            input.close();
        } 
    }
}

Upvotes: 1

user3424612
user3424612

Reputation: 183

There is no code in your example for actually collecting input, which leads me to believe you are not familiar with getting user input in Java. The Scanner class is a convenient way to handle this, and you can read more on that here: Java Scanner Tutorial.

You can use Scanner's nextLine() function to get a line of user input.

For example:

Scanner kb = new Scanner();
String userInput = kb.nextLine();
int length = country.length;

for(int i = 0; i < length; i++)
{
   if(userInput.equals(country[i]))
   {
      System.out.println(userInput + "'s " + " population is: " + population[i]);
   }
}

EDIT: You can place this inside some method, perhaps searchPopulation(String country), and call it inside a loop in main such as:

while(userChoice == true)
{
    System.out.println("Please enter a country: ");
    String userInput = kb.nextLine();
    searchPopulation(userInput);

   //Check if the user would like to keep going here
}

Of course, you would have to modify the first code example so that the name of the String matches the name provided in the method declaration, and remove the user input from the first code example since you are now handling it in the while loop.

EDIT: You may have something like this in your program:

import java.util.Scanner;

public class TestClass
{
    static String country[] = {"United States", "Brazil", "China", "Italy", "United Kingdom", "Spain", "Japan",              "Germany", "France", "Turkey", "South Africa", "Argentina"};;
    static int population[] = { 319111000, 203462000, 1367960000, 60783711, 64105654, 46507760, 127090000, 80767000, 66050000, 76667864, 54002000, 42669500};    

    public static void main(String args[])
    {
       boolean userChoice = true;
       String userInput = "";
       Scanner kb = new Scanner(System.in);

       while(userChoice == true)
        {
            System.out.println("Please enter a country: ");
            userInput = kb.nextLine();
            searchPopulation(userInput);

           //Check if the user would like to keep going here
        }

       kb.close();
    }

    public static void searchPopulation(String userInput)
    {
        int length = country.length;

        for(int i = 0; i < length; i++)
        {
           if(userInput.equals(country[i]))
           {
              System.out.println(userInput + "'s " + " population is: " + population[i]);
           }
        }
    }
}

With this, every time the loop iterates you ask the user for a country, then pass the country they entered to the method searchPopulation which searches for and outputs the population if the country is a match.

Upvotes: 0

John Pink
John Pink

Reputation: 637

You're looking for the user submitted country in your array to use the corresponding index :

for ( int i = 0; i < country.length; i++ ) { 
    if (country[i].equals(user_input)) {
        System.out.println(country[i] + "'s population: " + population[i]);
        break; // gets you out of the loop
    }
}

It's also a good programming habit to save an array's length in a variable as such :

for ( int i = 0, l = country.length ; i < l ; i++ ) {

Or else the array's length has to be calculated on each iteration.

Upvotes: 0

Related Questions