Определение динамической длины длинного массива - PullRequest
0 голосов
/ 16 февраля 2019

Я пытаюсь создать программу, которая вычисляет числовую последовательность итеративным способом.У меня трудности с определением динамического массива длины для моей длинной.При использовании ниже я получаю «отсутствие массива».Я что-то упускаю здесь очевидное?

Спасибо

long seq[] = new long[];

Полный код:

public long calculate(long n) {
        // If n is one of known values return that value
        if(n<=1){
            return 0;
        }
        if(n==2){
            return 1;
        }
        if (n==3){
            return 2;
        }

        // initate array to calculate
        long seq[] = new long[];
        int x = 0;
        seq[0] = 0;
        seq[1] = 0;
        seq[2] = 1;
        seq[3] = 2;

        // for loop until reached requested number
        for (int i = 4; i<=n; i++){
            seq[i] = seq[i-1]+seq[i-3];
        }
        for (int i =0; i<n; i++){
            x++;
        }
        return seq[x];
    }

Ответы [ 2 ]

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

Измерение пропущено, потому что, когда вы пишете [n], это одно измерение, а когда вы пишете [n,m], это двумерное, и оно идет вперед вот так ...

Когда вы просто передаете пустое [].он ничего не знает о том, как вы будете заполнять свой массив, поэтому либо вам нужно заполнить его на месте следующим образом: long[] powers = {..., 2863245995L, 11453115051L, ...}; long[] powers = {..., 2863245995L, 11453115051L, ...};

, либо установить размеры, что также означает, что вынужно установить размер.так как вам нужно использовать список чисел или разделенных запятыми чисел, каждый из которых представляет размер каждого измерения.например: long[] heights = new long[4];

, если вы хотите, чтобы он был массивом, и все же динамически изменять размер ... C # List сделайте это так, как я ЛИЧНО считаю, JAVA ArrayList должно бытьто же самое:

Initialize:
  create a array of default minimum size which is power of 2, 
  Set a used element count with name such as Count/Length to the number of element that are initially loaded otherwise 0

Adding element: 
  if there is more space, add to free slot, 
  if not, create new array and double the size
    then copy all item to the new array.
  Add to the Count/Length of array

В противном случае LinkedList выполнит работу, которую вы уже должны знать, как она работает ...

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

Вы не можете код

long seq[] = new long[];

вот так!Должна быть начальная емкость.

См. Источник ArrayList:

/**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer. Any
     * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     * will be expanded to DEFAULT_CAPACITY when the first element is added.
     */
    transient Object[] elementData; // non-private to simplify nested class access
    
    /**
     * Constructs an empty list with the specified initial capacity.
     *
     * @param  initialCapacity  the initial capacity of the list
     * @throws IllegalArgumentException if the specified initial capacity
     *         is negative
     */
    public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

    /**
     * Constructs an empty list with an initial capacity of ten.
     */
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

Если вы хотите динамически вставить:

/**
     * Inserts the specified element at the specified position in this
     * list. Shifts the element currently at that position (if any) and
     * any subsequent elements to the right (adds one to their indices).
     *
     * @param index index at which the specified element is to be inserted
     * @param element element to be inserted
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public void add(int index, E element) {
        rangeCheckForAdd(index);

        ensureCapacityInternal(size + 1);  // Increments modCount!!
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index);
        elementData[index] = element;
        size++;
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...