0

I working on my homework assignment, build code to queue with support of interface, I wrote my code but the output hade main.thread issue, to be honest I could not find the issue,however I do believe the issue is from insertion,mainly in the size increment, I appreciate some advice

public class MyQueue implements IntQueue {

    private int[] heltal;
    private int size;

    public void enqueue(int tal) {
// Inserts the specified element into the end of this queue.
// increases the size after every insertion 
        if (size == 0) {
            size++;
            heltal[0] = tal;
            int[] newArr = new int[heltal.length * 2];
            for (int i = 0; i < heltal.length; i++) {
                newArr[i] = heltal[i];
            }
            heltal = newArr;
        }
        return;
    }

    public int dequeue() throws NoSuchElementException {
// Returns the head of this queue and removes it. 
    // Throws an exception if this queue is empty.
        if (empty())
            throw new NoSuchElementException("The queue is empty");

        int NewValue = heltal[0];

        for (int i = 1; i < size; i++) {
            heltal[i - 1] = heltal[i];
        }
        heltal[size - 1] = 0;
        size--;
        return NewValue;
    }

    @Override
    public int peek() throws NoSuchElementException {
// Retrieves, but does not remove, the head of this queue.
    // Throws an exception if this queue is empty.
        if (empty())
            throw new NoSuchElementException("The queue is empty");
        return heltal[0];

    }

    @Override
    public boolean empty() {
// Checks if this queue is empty.
        return size == 0;

    }
}
Asaranow
  • 19
  • 5
  • There is so much wrong here. You only insert a value if the queue is empty, you always double the size of the queue, you're using a raw / array for an unbounded queue, and your question poses this as a thread related question, while none of the code involves threads or concurrency primitives. Deepak is correct however. If your enqueue method is executed the array is initially null causing `hental[0] = ...` to fail. – Keynan Jan 27 '20 at 00:40

1 Answers1

0

Initialize your array like below

private int[] heltal = new int[100];

and see if it works

Deepak Jain
  • 347
  • 1
  • 6