Java 包无法编译

Java Package Won't Compile

我认为我对如何设置 Java 包的理解可能遗漏了一些东西,因为我无法编译我的包。我有 3 个 class 个文件。我的目录如下所示:...Documents\jsjf 其中包含:ArrayStack.java 和 StackADT.java。在 jsjf 目录中,我还有一个文件夹 "EmptyCollectionException",其中包含 EmptyCollectionException.java。我可以编译 EmptyCollectionException.java 和 StackADT.java,但是当我尝试编译 ArrayStack.java 时,我收到以下错误消息(请参阅 link):http://i.stack.imgur.com/koJ8P.jpg

这是每个文件的每个代码部分的顶部。有谁知道这里的问题是什么。为什么 ArrayStack 无法导入包?

对于ArrayStack.java

package jsjf;



import jsjf.EmptyCollectionException;
import java.util.Arrays;

public class ArrayStack<T> implements StackADT<T>
{
   private final int DEFAULT_CAPACITY = 100;
   private int top;
   private T[] stack;



   //-----------------------------------------------------------------
   //  Creates an empty stack using the specified capacity.
   // Note top is now initialized at -1 so that when first
   // element is added an top is decremented, top will equal 0
   // corresponding to the array index of the first element.
   //-----------------------------------------------------------------
   public ArrayStack(int initialCapacity)
   {
      top = -1;
      stack = (T[]) (new Object[initialCapacity]);
   }

   //-----------------------------------------------------------------
   //  Creates an empty stack using the default capacity.
   //-----------------------------------------------------------------
   public ArrayStack()
   {
      this(DEFAULT_CAPACITY);
   }


//Rest of code.......

对于EmptyCollectionException.java:

package jsjf.exceptions;


public class EmptyCollectionException extends RuntimeException
{
    /**
     * Sets up this exception with an appropriate message.
     * @param collection the name of the collection
     */
    public EmptyCollectionException(String collection)
    {
        super("The " + collection + " is empty.");
    }
}

对于 StackADT:

package jsjf;


public interface StackADT<T>
{
    /**  
     * Adds the specified element to the top of this stack. 
     * @param element element to be pushed onto the stack
     */

    //Rest of Code

你的代码说你希望 EmptyCollectionException 在包 jsjf 中,但你说 class 存在于子文件夹中,这在包层次结构中更深(并违反 Java 命名约定,其中包名称通常不是驼峰式)。

你的 EmptyCollectionException class 代码说它在 jsjf.exceptions 包中,意思是 (a) 它应该在 jsjf 下的 exceptions 文件夹中文件夹,您导入的 EmptyCollectionException 应该是 import jsjf.exceptions. EmptyCollectionException.

您还需要在编译时位于合理的位置,例如,您的文档文件夹,因为包将位于您编译的位置 "underneath"。就个人而言,我会把它放在一个更合理的文件夹位置,最好没有空格,不要放在 Windows 文档文件夹下。

首先,包名不能以大写开头。它会帮助您看到 jsjf.EmptyCollectionException 不指向层次结构中的 class 而是指向一个包。因此,根据 Java 命名约定重命名包后,正确的导入应该是:

import jsjf.emptyCollecionException.EmptyCollectionException

在你的例外 class 中,你使用了另一个包名 (exceptions)。包名称应与父目录的名称相匹配。因此,我会将包含 EmptyCollectionException 的目录重命名为 exception 并修复 ArrayStack.

中的导入

最后,我强烈建议您使用 IDE,因为您手动编译了一些 classes 只是为了了解它是如何工作的。 IDE 将帮助您进行导入、编译和许多其他事情