繁体   English   中英

“无效的方法声明; 尝试调用方法时返回“需要返回类型”

[英]“invalid method declaration; return type required” when trying to call a method

我是Java的新手,在整理列表时遇到一些问题。 我必须编写Iterable类,以便当您遍历队列时,它以随机顺序返回项目。 这就是为什么我编写该shuffle方法,然后在RandomizedQueueIterator类中调用它的原因

import java.util.Iterator;
import java.util.NoSuchElementException;
public class RandomizedQueue<Item> implements Iterable<Item>
{
    // instance variables
    private Item[] queue;
    private int N = 0;
    private int R = 0;


    // constructor
    public RandomizedQueue()
    {
        queue = (Item[]) new Object[1];
    }


    // helper functions
    private void resize(int capacity)
    {
        Item[] copy = (Item[]) new Object[capacity];
        for (int i = 0; i < N; i++)
            copy[i] = queue[i];
        queue = copy;
    }

    private void shrink(int capacity)
    {
        Item[] copy = (Item[]) new Object[capacity];
        int M = 0;
        for (int i = 0; i < N; i++)
        {
            if (queue[i] != null)
                copy[M++] = queue[i];
        }
        queue = copy;
    }   

    // shuffle queue
    private void shuffle(Item[] a )
    {
        int N = a.length;
        for (int i = 0; i < N; i++)
        {
            int r = StdRandom.uniform(i + 1);
            Item temp = a[r];
            a[r] = a[i];
            a[i] = temp;
        }
    }


    // return wether queue is empty
    public boolean isEmpty()  {  return queue.length == 0;   }


    // return size of queue
    public int size()   {   return queue.length;   }


    // add item to the queue
    public void enqueue(Item item)
    {
        if (N == queue.length)   {   resize(N*2);   }   
        queue[N++] = item;
    }


    // remove and return a random item from the queue
    public Item deque()
    {   
        // generate a random index and store item
        int random_index;
        do  {
            random_index = StdRandom.uniform(0, N);                            
        } while (queue[random_index] == null);

        Item item = queue[random_index];

        // delete item from array and increment counter of null items
        queue[random_index] = null;
        R += 1;

        // shrink array if corresponds
        if (R == (3/4 * N))   {   shrink(N/2);   }

        // return item
        return item;
    }    

    // return a random item from the queue
    public Item sample()
    {   
        // generate a random index and store item
        int random_index;
        do  {
            random_index = StdRandom.uniform(0, N);                            
        } while (queue[random_index] == null);

        Item item = queue[random_index];

        // return item
        return item;       
    }


    // iteration
    public Iterator<Item> iterator()  
    {  
        return new RandomizedQueueIterator();      
    }

    private class RandomizedQueueIterator implements Iterator<Item>
    {
        private int i = 0;
        shuffle(queue);


        public boolean hasNext()   
        {  
            return i < N;  
        }

        public Item next()
        {   
            if (i >= N)
            {
                throw java.util.NoSuchElementException; 
            }
            return queue[i++];

        }

        public void remove()
        {
            throw new UnsupportedOperationException("Invalid operation for array");
        }    
    }


    // main method
    public static void main(String[] args)
    {
        RandomizedQueue example = new RandomizedQueue();
        example.enqueue(0);
        example.enqueue(1);
        example.enqueue(2);
        example.enqueue(3);
        example.enqueue(3);
        example.enqueue(3);
        example.enqueue(3);
    }   
}

尝试编译时的输出:

2 errors found:

[line:114]错误:方法声明无效; 需要返回类型

[line:114]错误:预期

行:114>随机播放(队列);

任何帮助将非常感激。 谢谢

如果要运行类,则需要将方法调用放入主方法中

public static void main(String...args) {
   shuffle(list_test);
}

如果执行此操作,则可以将list_test定义为static变量,或者在main方法中定义它。

有几个问题。 问题之一是您在类内部而不是在函数中调用函数方法。 创建test对象后,应该在外部调用该函数。

所以在你的主。 呼叫:

 list_test = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
 test testObj = new test();
 newList = test.shuffle(list_test); // in the case it returns a new list

哪里

  private void shuffle(int[] a )
     // and returns a new list
     return shuffled_list

如果只关心列表中的项目改组,请改用JDK内置的shuffle()方法。

有很多事情可以改进。 您的课程可能如下所示:

import java.util.Arrays;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Random;

// it is standard to use E or T for collections
public class RandomizedQueue<E> implements Iterable<E> {

  // most java collections have a default size of 16, set at 2 for testing
  private static final int DEFAULT_INITIAL_CAPACITY = 2;
  private static final Random GENERATOR = new Random();

  // have good variable names
  private boolean iterating = false; // to avoid concurrent modification
  private E[] queue;
  private int size = 0;

  @SuppressWarnings("unchecked")
  public RandomizedQueue() {
    queue = (E[]) new Object[DEFAULT_INITIAL_CAPACITY];
  }

  // remove and return a random item from the queue
  public E dequeue() {
    if (iterating) {
      throw new ConcurrentModificationException();
    }
    return dequeue(GENERATOR.nextInt(size));
  }

  // add item to queue
  public void enqueue(E item) {
    if (iterating) {
      throw new ConcurrentModificationException();
    }
    if (size == queue.length) {
      resize(size * 2);
    }
    queue[size++] = item;
  }

  // return whether queue is empty
  public boolean isEmpty() {
    return size == 0;
  }

  // iteration
  public Iterator<E> iterator() {  
    return new RandomizedQueueIterator();      
  }

  // return a random item from the queue
  public E sample() {
    if (isEmpty()) {
      throw new NoSuchElementException("trying to sample from empty queue");
    }
    return queue[GENERATOR.nextInt(size)];       
  }

  // shuffle queue
  public void shuffle() {
    for (int i = size - 1; i >= 0; i--) {
      swap(i, GENERATOR.nextInt(i + 1));
    }
  }

  // return size of queue
  public int size() {
    return size;
  }

  // helper functions

  private E dequeue(int randomIndex) {
    if (isEmpty()) {
      throw new NoSuchElementException("trying to remove from empty queue");
    }

    size--;
    // resize if only 1/4 of the queue is full
    if (size < queue.length / 4) {
      resize(queue.length / 2);
    }

    // since all get data methods are random, only need to swap on remove
    swap(randomIndex, size);
    E randomItem = queue[size];
    queue[size] = null;
    return randomItem;
  }

  private void resize(int capacity) {
    // copyOf is substantially faster since it uses arraycopy which is in native code
    queue = Arrays.copyOf(queue, capacity);
  }

  // swap data at indices i and j
  private void swap(int i, int j) {
    E temp = queue[j];
    queue[j] = queue[i];
    queue[i] = temp;
  }

  private class RandomizedQueueIterator implements Iterator<E> {
    private int currentIndex = 0;
    private int indexToRemove = -1;

    private RandomizedQueueIterator() {
      iterating = true;
      shuffle();
    }

    public boolean hasNext() {
      return currentIndex < size;
    }

    public E next() {
      if (currentIndex >= size) {
        throw new NoSuchElementException();
      }
      indexToRemove = currentIndex;
      E nextElement = queue[currentIndex++];
      if (currentIndex == size) {
        iterating = false;
      }
      return nextElement;
    }

    public void remove() {
      if (indexToRemove == -1) {
        throw new IllegalStateException();
      }
      // print for testing
      System.out.println("r: " + dequeue(indexToRemove));
      currentIndex--;
      indexToRemove = -1;
    }
  }

  // main method
  public static void main(String[] args) {
    int exampleSize = 7;

    System.out.println("example 1:");
    RandomizedQueue<Integer> example1 = new RandomizedQueue<>();
    for (int i = 0; i < exampleSize; i++) {
      example1.enqueue(i);
    }
    System.out.println("size: " + example1.size());

    for (int i = 0; i < exampleSize; i++) {
      System.out.println("d: " + example1.dequeue());
    }
    System.out.println("size: " + example1.size());

    System.out.println("\nexample 2:");
    RandomizedQueue<Integer> example2 = new RandomizedQueue<>();
    for (int i = 0; i < exampleSize; i++) {
      example2.enqueue(i);
    }
    System.out.println("size: " + example2.size());

    Iterator<Integer> iterator = example2.iterator();
    // iterator.remove(); throws IllegalStateException
    while (iterator.hasNext()) {
      System.out.println("i: " + iterator.next());
      iterator.remove();
      System.out.println("size: " + example2.size());
      // iterator.remove(); should throws IllegalStateException
    }
  }
}

使用它为您提供有关如何编写课程的想法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM