d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Array Help
Add Reply New Topic New Poll
Member
Posts: 3,466
Joined: Jul 22 2012
Gold: 30,884.00
Mar 20 2018 07:46pm
Need to create a method that uses loop and return name of province that has lowest pop.

I have accessors for province's name and pop in another class. So far I only came up with:

public int getLowPop()
{
int pop = provinces[0].getPopulation();
for(int i = 1; i < provinces.length; i++)
{
if(provinces.getPopulation() < lowestPop)
{
lowestPop = provinces.getPopulation();
}
}
return pop;
}
}

So my code returns lowest population from an array, but I don't know how to return the name of it.

Array example:


provinces[0] = new PT("British Columbia", 87414);
provinces[1] = new PT("Alberta", 23245);
provinces[2] = new PT("Manitoba", 983);
provinces[3] = new PT("Saskatchewan", 8758);
Member
Posts: 2,754
Joined: Nov 26 2007
Gold: 1,339.81
Mar 21 2018 01:18pm
Change the return type of getLowPop() to String.
Return lowestPop.getName() // this is assuming PT has a function called getName().
Member
Posts: 3,466
Joined: Jul 22 2012
Gold: 30,884.00
Mar 21 2018 07:33pm
it says int cannot be deferenced for:

return lowestPop.getName();


I have getName() for PT class too.
Member
Posts: 3,648
Joined: May 16 2010
Gold: 21,113.33
Mar 22 2018 12:47pm
Code
import java.util.ArrayList;

public class Main {


public static void main(String[] args) {

ArrayList<Population> provinces = new ArrayList<Population>();

provinces.add(new Population("BC", 100));
provinces.add(new Population("DC", 1100));
provinces.add(new Population("CC", 300));
provinces.add(new Population("AC", 200));


Population lowPop = getLowPop(provinces);
System.out.println(lowPop.getName() + lowPop.getPopulation());
}

public static Population getLowPop(ArrayList<Population> pop) {

Population startPop = pop.get(0);

for (int i = 1; i < pop.size(); i++) {
if (startPop.population > pop.get(i).population) {
startPop = pop.get(i);
}
}

return startPop;
}
}


Pop Class
Code
public class Population {
String name;
int population;

public Population(String name, int population) {
this.name = name;
this.population = population;
}

//Don't really need these get methods. Since you can directly reference
//using pop.name or pop.population
public int getPopulation() {
return population;
}

public String getName() {
return name;
}
}


Don't know if this is what you are looking for or not.

Output was BC100

I tend to use ArrayList when making an array of objects.

Pm me if this helped or not.

This post was edited by SEALs on Mar 22 2018 12:50pm
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll