Hi, I have a lab due Tuesday and I would like some help. This project has 2 classes: StateProvince and Country. In the Country class there is a method called, "public int howManyHaveThisPopulation(int min, int max)" which takes the population in millions(e.g. 4, 6) and returns how many StateProvinces there are with populations in that range(e.g. 4-6 million, inclusive). So I started it and can't get it to work. We are supposed to use a For loop not a While loop. We could use a While loop but then the last part of our assignment is to change While loops to For loops since this is our lesson. I will post the class below if someone wouldn't mind having a look. Lines 51-64 are where I would need help. If I try and compile, Java's warning is: "variable min is already defined in method howManyHaveThisPopulation(int,int)". So I know this is wrong:
Harry Peters wrote:Lines 51-64 are where I would need help. If I try and compile, Java's warning is: "variable min is already defined in method howManyHaveThisPopulation(int,int)". So I know this is wrong:
You are not allowed to declare two local variables (in a method) with the same name. In this case, you have a "min" parameter, which is also a local variable. And later, a couple of lines later, you are trying to declare another local variable, named "min".
Harry Peters wrote: Here is what I did, and BlueJ says I'm missing a return statement.
Well, first, I agree the code doesn't make much sense... but... in terms of the compile error, with Java, when you declare that a method returns a type, it *must* return that a value of that type. And this is true for all possible code paths.
In your code, it is possible for either loop's condition to never be true (as detected at compile time), and hence, the code would end up after the two loops -- and in a section of code, that does not have a return statement. Or in other words, the compiler is complaining that it is possible for the method to execute in a way that doesn't encounter a return statement.
I would prefer to use an array initiliaser to individual assignments.Not only is it shorter, but it guarantees that the size of the array will match the number of elements. No out of bounds exception because you tried to enter too many elements. No nulls because you entered too few.