Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getCountry method error

Tags:

java

arrays

Can someone offer some insight on why the code doesnt work? the problem lies in the part countries [numCountries]=newCountry;

I'm not sure why it keeps saying type mismatch cannot convert Country[] to Country, but I thought my countries[numCountries] is Country[] type since I already called it at the 2nd line of code as that type?

public class World{

private Country[] countries;
private int numCountries=0;

public boolean addCountry(Country[] newCountry){
    if(!(newCountry==null)){
        countries[numCountries]=newCountry;     //the newcountry part doesnt work, red zigzag line underlining it here im not sure why
        numCountries++;
        return true;
    }
    else
        return false;

       }


}
like image 431
Liquified Avatar asked May 30 '26 08:05

Liquified


1 Answers

You method says that you're adding a Country, not adding an array of Country, so your method parameter should probably lose the array brackets []. This way the method makes much more sense, since it passes in what you say should be passed in -- a single Country object. You'll also want to check in your method that you're not exceeding the size of the countries array before attempting to add another Country to the array. This can be done with a simple if statement.

If you want to add an array of Country, then you may wish to create another method, say addCountries(Country[] newCountries). But I don't think that you really want to do this, so stick with the corrected current method.

If any of this doesn't make sense, please ask -- just write a comment below this answer.

like image 93
Hovercraft Full Of Eels Avatar answered Jun 01 '26 21:06

Hovercraft Full Of Eels



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!