Манипуляции с массивом начинающих - PullRequest
0 голосов
/ 20 февраля 2019

У меня проблемы с одним из моих заданий.Я выполнил код и должен отправить задание, которое автоматически оценит его, используя несколько тестов.Я получил все, кроме двух, чтобы пройти.Я не знаю код для тестов.Я предполагаю, что это происходит от этого метода:

/**
 * _Part 2: Implement this method._
 *
 * @return the number of items in the list.
 */
public int size() {
    int size = 0;       //int holder for size of elements in array
    for (int i = 0; i < array.length; i++){     //loop to run through up to length of array
        if(array[i] != null){           //if data at array index has a value, increase int size
            size++;
        }
        else{           //if data at array index has no value, there are not anymore elements to check for
            break;
        }
    }
    return size;        //returning the number of elements in the array
}

Вот ошибки, которые я получаю:

Starting: insertTwoItems
Failed: insertTwoItems
 Hint: Size should be 2 after two inserts! expected:<2> but was:<1>
Finished: insertTwoItems

Starting: insertThreeItems
Failed: insertThreeItems
 Hint: Size should be 2 after two inserts! expected:<2> but was:<1>
Finished: insertThreeItems

Конструктор просто: array = new String [10];

Вот так я вставляю новые строки в массив

@SuppressWarnings("unchecked")
/**
 * _Part 1: Implement this method._
 *
 * Inserts a new item in the OrderedArrayList. This method should ensure
 * that the list can hold the new item, and grow the backing array if
 * necessary. If the backing array must grow to accommodate the new item, it
 * should grow by a factor of 2. The new item should be placed in sorted
 * order using insertion sort. Note that the new item should be placed
 * *after* any other equivalent items that are already in the list.
 *
 * @return the index at which the item was placed.
 */
public int insert(String item) {
    if(array.length <= size()){         //checking if string array is full
        String[] tempArray = array;     //creating a temp string array, to make this.array bigger
        array = new String[array.length*2];     //doubling the length of array

        for(int i = 0; i < tempArray.length; i++){      //putting tempArray values back into original array
            array[i] = tempArray[i];
        }
    }

    for(int i = 0; i < array.length; i++){      //loop to find location to add item into
        if(array[i] == null){       //if array index location is null, then put item in that spot.
            array[i] = item;
            return i;               //returning index location item was put at
        }
        if(item.compareTo(array[i]) < 0){       //will only insert until array index is alphabetically smaller than item
            for(int j = size()-1; j > i; j--){      //moving all items from array size down to index j
                array[j+1] = array[j];          //copying left index into right index

            }
            array[i] = item;        //once all indexes from where item should go is moved to the right, index is put in the array
            return i;               //returning index of array where item went
        }
    }

    return 1000000;     //not necessary, but cannot compile without a return outside of loops. Should not reach this
}

Я не уверен, для чего предназначено предупреждение о подавлении.Кто-нибудь видит какие-либо ошибки в моем коде, которые могут повлиять на неудачу в тестах, показанных выше?

1 Ответ

0 голосов
/ 20 февраля 2019

Проблема из этой части.

for(int j = size()-1; j > i; j--){      //moving all items from array size down to index j   
    array[j+1] = array[j];             //copying left index into right index
}

Назначение j неверно.Так как, например, у вас есть массив ['a','z'], и вы собираетесь вставить 'c'.j будет иметь значение 1, а значение вашего i также равно 1, поэтому оно не попадет внутрь цикла.Вы должны изменить его на это.

for (int j = size(); j >= i; j--) { // moving all items from array size down to index j
    array[j] = array[j - 1]; // copying left index into right index
}

Теперь значение j будет равно 2, а значение i равно 1, таким образом, оно попадет в ваш цикл.Затем вы делаете копирование левого указателя в правый указатель.

Также относительно этого.

return 1000000;

Это действительно необходимо, но ваше возвращение должно быть -1.Возвращение -1 означает, что элемент не был вставлен, поскольку -1 не является допустимым индексом в массиве.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...