java - 导出的可运行 Java 程序不适用于 main 方法
问题描述
我从我的 Java 练习册中创建了一个小游戏,当我在 Eclipse 中编译它时它运行良好,但是一旦我添加 main 方法并将其作为 .jar 导出到我的桌面上,当我双击它时它不起作用,也它在命令控制台上工作吗?我似乎无法导出任何功能的 .jar 程序,尽管它们在 Eclipse 中编译得很好。我假设我在使用主要方法时做错了什么?
import acm.program.*;
import acm.util.*;
import java.awt.Color;
import acm.graphics.*;
public class CrapsGameTest extends ConsoleProgram{
public static void main (String[] args){
CrapsGameTest craps = new CrapsGameTest();
craps.run();
}
public void run() {
/*if total = 2, 3, or 12 you loose
* if total = 7 or 11 you win
*
* */
setFont("Helvetica-40");
int total = rollTwoDice();
if (total == 2 || total == 3 || total==12) {
println(total +" You loose");
} else if (total == 7 || total == 11) {
println(total +" You win");
} else {
//saves points under the initial TOTAL variable
int points=total;
println("your point total is " + points);
//initializes step by step rolls with i++
int i = 0;
while(i>=0) {
int x = readInt("Roll again?");
if (x==1) {
i++;
}
//changes the total variable by rolling dice.
//if the new total variable = points then you win:
//after every loop "total" variable changes due to the rollTwoDice method.
total = rollTwoDice();
if (points ==total) {
println("You win!");
break;
} else if (total == 7) {
println("you loose");
break;
}
}
}
int y = readInt("Do you wish to play again?");
if (y == 1) {
run();
}
}
private int rollTwoDice() {
int d1 = rgen.nextInt(1,6);
int d2 = rgen.nextInt(1,6);
int total = d1 + d2;
println("Rolling dice: " + d1 + " + "+d2 + " = " + total );
return total;
}
//initializes rgen variable
private RandomGenerator rgen = new RandomGenerator();
}
解决方案
根据这份文件:
Java 程序需要从类中的特定方法开始,即 public static void main(String[] args) 方法。如果您的程序使用 ACM 库,则需要编辑代码以具有 main() 。您可以通过简单地将以下代码添加到具有公共 void run() 的类中轻松地做到这一点,用该类的名称替换下面的类。
public static void main (String[] args){
new CrapsGameTest().start(args);
}
经过这个小改动后,您的导出应该可以正常工作了。
推荐阅读
- websocket - 如何通过 graphql 订阅广播 websocket 数据
- regex - 如何从单元格的第 n 行中提取所有内容?(在工作表中使用正则提取)
- excel - 使用 VBA 更改可变单元格但是我想更改另一个单元格,第二个单元格更改第一个
- r - 为组中的每个级别自动化 ggplot
- c++ - 如何在 Qt c++ Combobox 中获取当前文本的 id?
- reactjs - 下一个 js getServerSideProps 使用 props 重定向
- arrays - 使用 JQ 通过索引从数组中的项形成新数组
- amazon-web-services - AWS:从 Application LoadBalancer 获取 502 到 EC2 实例
- python - 使用 LSTM/RNN 预测数字序列
- database - 通过猫鼬连接到 MongoDB