0

I have to add a String parameter to the end of an array. And throw an exception if the String already exists in the array. I don't know. Can anyone help? This is what I have so far

public static void addCity (String city) throws Exception
{
    for (int i = 0; i < MAX_CITIES;i++)
    {
        if (city == cityNames[i])
            throw new Exception("This city already exists");
    }

    String [] temp = new String[cityNames.length+1];
    for (int i = 0; i < cityNames.length;i++) {
        temp[i] = cityNames[i];
    }
    temp[temp.length-1] = city;
    cityNames = temp;

    manyItems++;
}
1
  • 2
    What problem are you getting? And ideally if you want to implement dynamically increasing array.. Use ArrayList instead.. Commented Oct 6, 2012 at 18:53

4 Answers 4

2

To test if String a equals String b, use a.equals(b), not a == b.

(a == b works in C++, not Java.)

Sign up to request clarification or add additional context in comments.

Comments

0

Your code looks fine except for the String comparison:

if (city == cityNames[i])

This won't do a proper String comparison: it will only compare the object references, which will usually be false.

Use String.equals for this:

if (city.equals(cityNames[i]))

Comments

0

It'd be easier to use a List:

List<String> cityNames = new ArrayList<String>();

if(cityNames.contains(city)) {
    throw new Exception("This city already exists");
}
cityNames.add(city);

1 Comment

Looks like OP is in learning phase (otherwise using plain arrays with an increment of 1 will be very very bad).
0

What is MAX_CITIES? I think your first loop should be until i < cityNames.length, not MAX_CITIES, since you don't seem to be updating MAX_CITIES when you increase the size of the array.

You should be using the equals() method to compare String objects, rather than ==.

It also might be nice if instead of just making the new array one element bigger, you double the size. That way you don't have to go through all the work of copying the array every time you add a new element. You'd need a variable to keep track of the next empty spot in the array, and it would look something like this:

if (nextEmptyIndex == cityNames.length)
{
    String [] temp = new String[cityNames.length*2];
    for (int i = 0; i < cityNames.length;i++) {
        temp[i] = cityNames[i];
    }
}
temp[nextEmptyIndex] = city;
nextEmptyIndex++;
manyItems++;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.