gpt4 book ai didi

Java 包无法编译

转载 作者:行者123 更新时间:2023-12-01 22:09:44 24 4
gpt4 key购买 nike

我认为我对如何设置 Java 包的理解可能缺少一些东西,因为我无法编译我的包。我有3个类文件。我的目录如下所示:...Documents\jsjf 其中包含:ArrayStack.java 和 StackADT.java。在 jsjf 目录中,我还有一个文件夹“EmptyCollectionException”,其中包含 EmptyCollectionException.java。我可以编译 EmptyCollectionException.java 和 StackADT.java,但是当我尝试编译 ArrayStack.java 时,我收到以下错误消息(请参阅链接): /image/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

最佳答案

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

import jsjf.emptyCollecionException.EmptyCollectionException

在异常类中,您使用另一个包名称(exceptions)。包名称应与父目录的名称匹配。因此,我将包含 EmptyCollectionException 的目录重命名为 exception 并修复 ArrayStack 中的导入。

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

关于Java 包无法编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32061838/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com