学习Java类和方法,在测试代码时出现此错误



我正在学习CS101的JAVA书,并试图理解这个练习,但当我运行代码时,我不断收到这个错误

错误:无法找到或加载主类Riddle

原因:java.lang.ClassNotFoundException:Riddle

JAVA代码

public class Riddle{
private String question;        //instance variables
private String answer;

public Riddle( String q, String a)      //constructor
{
question = q;
answer = a;
}

public String getQuestion()     //instance method
{
return question;
}

public String getAnswer()
{
return answer;
}
}

public class RiddleUser{
public static void main ( String argv [] ){
Riddle riddle1= new Riddle (
"What is black and white and red all over?",
"An embarrassed zebra.");
Riddle riddle2= new Riddle (
"What is black and white and read all over?",
"A newspaper." );

System.out.println("Here are two riddles:");
System.out.println(riddle1.getQuestion());
System.out.println(riddle2.getQuestion());
System.out.println("The answer to the first riddle is:");
System.out.println(riddle1.getAnswer());
System.out.println("The answer to the second riddle is:");
System.out.println(riddle2.getAnswer());
}
}

这是我正在做的练习,我还上传了这本书的PDF,练习在71-73页。基本上,它想向你展示如何编写一个类并对其进行测试,如果我没有错的话。

在此处输入图像描述

在此处输入图像描述

在此处输入链接描述

在Java文件中,只有一个类可以是公共的,公共类是具有main方法的类。

文件和公共类必须具有相同的名称,在本例中为RiddleUser.java。

在自己的文件中声明RiddleUser类之后。

如果您将private作用域修饰符添加到RiddleUser类中,而不在其自己的文件中声明它,那么这应该会起作用。

假设您的源路径文件夹是~/riddle-project/src/

riddle-project
└── src
├── Riddle.java
└── RiddleUser.java

执行以下操作:

# compile main class
$ javac src/Riddle.java
# run main class with specified class path 
$ java -classpath ./src/ Riddle

类路径是包含.class编译的java文件的目录

最新更新