【发布时间】:2014-09-09 22:57:21
【问题描述】:
最近开始为考试学习 Java。
在学习包时,尝试了这个并收到错误消息。我所做的是,
//Creating class A (Within package the package: com.test.helpers)
package com.test.helpers;
public class A {
public void sayHello(){
System.out.println("Hello World");
}
}
//And then the class App utilizing the class A
import com.test.helpers.*;
public class App{
public static void main(String args[]){
A a = new A();
a.sayHello();
}
}
我将这两个文件放在一个名为“JavaTest”的目录中(在 Windows 7 上),
并首先使用命令javac -d . A.java编译A.java
然后,在尝试编译 App.java 时,我收到以下错误消息:
App.java:5: error: cannot access A
A a = new A();
^
bad source file: .\A.java
file does not contain class A
Please remove or make sure it appears in the correct subdirectory of the source path.
1 error
不过,问题似乎可以通过两种方式解决,
- 删除源文件 A.java
- 将导入语句从
import com.test.helpers.*;更改为import com.test.helpers.A在文件“App.java”中。
如果您能解释一下这里发生了什么,我将不胜感激。或者我可能犯了一个愚蠢的人为错误或语法错误。
Here's the link to the source files
非常感谢
【问题讨论】:
-
class App在默认包里吧?
-
是的,我相信是的。目录结构是这样的(编译A.java后)Desktop>JavaTest -com>test>helpers>A.class -A.java -App.java 谢谢你抽空看一下。
-
emmh,我看不到目录结构,但是 A 类应该在路径 JavaTest\com\test\helpers\A.java 中,是吗?
-
对不起,第一条评论没有清楚地显示类结构。源文件(A.java 和 App.java)位于名为“JavaTest”的文件夹中。 A.Java编译完成后,它的class文件出现在JavaTest>com>test>helpers里面。尝试编译App.java时出现错误如果A.java被删除或App.java中的import语句发生更改就可以了,将星号替换为显式类名,即A. Btw,感谢您抽出宝贵时间看看。
-
顺便说一下,如果你愿意,这里是项目的下载链接:link 谢谢。