Java 错误 - 源文件错误 : file does not contain class x . 请删除或确保它出现

标签 java import package

最近开始学习 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 utilising 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
<小时/>

但是,问题似乎可以通过两种方式解决,

  1. 删除源文件A.java
  2. 将文件 App.java< 中的导入语句从 import com.test.helpers.*; 更改为 import com.test.helpers.A/

如果您能解释一下这里发生的情况,我将不胜感激。或者我可能会犯一个愚蠢的人为错误或语法错误。

Here's the link to the source files

最佳答案

您好,这里的问题是 JVM 混淆了类文件,因为目录中的类文件名不明确(JavaTest com.test.helpers 目录)。

当你执行javac -d 时。 A.java 编译器在 com.test.helpers 目录中生成一个类文件,现在它将它与 JavaTest

中的源文件混淆了
  1. 删除源文件A.java

当您从 JavaTest 中删除源文件 A.java 时,JVM 现在知道 com.test.... 中的类文件> 被使用,歧义就会消失。

  • 将导入语句从“import com.test.helpers.*;”更改为在文件“App.java”中“导入 com.test.helpers.A”。
  • 在这里,您指定在类实现中使用哪个特定文件,即告诉编译器使用来自 com.test... 的文件 A.java > 而不是来自 JavaTest

    现在,这种歧义的解决方案对您来说永远不会成为问题,您必须使用 import 语句导入特定文件,即 import com.test.helpers.A; 或者如果您想do import com.test.helpers.*; 那么你必须专门使用 com.test.helpers.A 来代替 A当前类实现,告诉编译器不要将其与 JavaTest

    中的源代码混淆

    我知道这个特定的答案已经很晚了,但我想与即将到来的读者分享我的观点,如果它能以任何方式帮助他们,那就太好了。 谢谢!

    关于Java 错误 - 源文件错误 : file does not contain class x . 请删除或确保它出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61825374/

    相关文章:

    r 包开发 - opencpu 看不到自己的功能

    Java:如何传递对新运算符的引用?

    java - Spring 3.2 @Configurable 和@Autowire 无法注入(inject)任何东西

    Java JSON包导入失败

    javascript - 代码未在 Javascript 模块类型脚本源内执行 [ES6]

    mysql - 我无法从文件中加载仅包含整数列的 MySQL 表

    .net - Sitecore 软件包生成

    java - Java并发,Akka和RxJava之间的区别?

    java - ARCore ArSceneView 捕获位图

    sql-server - 尝试从 Excel 导入时出现截断错误