I need to find another way to comunicate the more populated city of an array. The code is like this but sometimes he give me the right city name, and sonetimes he give me the wrong city name, does somebody have any idea?
public class Esercizio32_101
{
public static void main(String[] args)
{
// Object for InputStream
ConsoleReader2 tastiera = new ConsoleReader2(System.in);
// declarations
String names[] = new String[5];
int population[] = new int[5];
String n = null;
int higher = 0;
int total = 0;
int c = 0;
// calcoli
for (int i = 0; i < names.length; i++)
{
System.out.print("Insert the name of city N° " + (i + 1) + " ===> ");
do
{
names[i] = tastiera.readLine();
if (names[i].equals(""))
{
System.out.print("You must insert the city name, try again ===> ");
}
}
while (names[i].equals(""));
}
for (int i = 0; i < names.length; i++)
{
System.out.print("Insert the population of city N° " + (i + 1) + " ===> ");
population[i] = tastiera.readInt();
total = population[i];
if (total > higher)
{
higher = total;
c++;
}
}
System.out.print("The most populated city is " + names[c]);
}
}
The most immediate problem is here:
if (total > higher)
{
higher = total;
c++;
}
By incrementing c
you're just remembering how many cities had a larger population than any of the preceding ones. You want to remember the index of the more populous city:
if (total > higher)
{
higher = total;
c = i;
}
Additionally, I would strongly advise you to create a City
type to encapsulate the "name and population". Ask for all the city details to populate a List<City>
or a City[]
, and then you can find the most populous city. Any time you find yourself with multiple collections which will all have the same size, you should consider refactoring to one collection with a type that encapsulates one value for each of the original collections.
That approach will also encourage you to separate "data gathering" from "data processing" - currently you're detecting the largest population while you're asking the user for input. That means if you later wanted to handle the situation where the data was loaded from disk, you'd need to rewrite things. If you separate out the different concerns, it'll make your code easier to modify and test.
Finally, I'd suggest you think more carefully about variable names. In what way does total
communicate the intent of "the population of the city I'm asking about at the moment"?
See more on this question at Stackoverflow