我正在练习编程课程。我得到一个看似非常基本的奇怪错误,但我无法调试它。
引用时,代码会创建标准的StopWatch对象,并使用与之关联的多个实例方法。我在代码的底部创建了一个main方法,以便测试StopWatch类中的每个方法,以确保它正常工作。
目前,当我运行该程序时,我收到一条错误消息:
Exception in thread "main" java.lang.NoSuchMethodError: main.
我在这个课程中显然有一个主要的方法,所以我不确定为什么我会收到这个错误。
主要方法实现了Gambler的破产程序进行测试。我目前正在尝试测试stop()和elapsedTime()方法。完整代码包含在下面:
/* Notes:
* Start is the date of birth of the object. Most stopwatch don't keep track of when they were
* created.
*/
public class Stopwatch {
public long startTime; //The creation time of the stopwatch
public long totalTime; //Total time since watch was zeroed
boolean running = false; //This will flag if the watch is started or stopped
public Stopwatch() //First instance method called Stopwatch. What the client will use to create Stopwatch. This serves as the constructor.
{
start();
}
public void start()
{
startTime = System.currentTimeMillis();
running = true;
}
public void stop()
{
if(running) {
totalTime += System.currentTimeMillis() - startTime;
running = false;
}
}
public double elapsedTime()
{
if(running){
return System.currentTimeMillis() - startTime;
}
else{
return 0; //If the watch isn't currently running, return a 0 value.
}
}
public void zero()
{
totalTime = 0;
start();
}
public static void main(String[] args)
{
// Run T experiments that start with $stake and terminate on $0 or $goal.
Stopwatch program_time = new Stopwatch();
int stake = Integer.parseInt(args[0]);
int goal = Integer.parseInt(args[1]);
int T = Integer.parseInt(args[2]);
int bets = 0;
int wins = 0;
for (int t = 0; t < T; t++)
{
// Run one experiment
int cash = stake;
while (cash > 0 && cash < goal)
{
// Simulate one bet.
bets = bets + 1;
if (Math.random() < 0.5)
{
cash = cash + 1;
}
else
{
cash = cash - 1;
}
} // Cash is either going to be at $0 (ruin) or $goal (win)
if (cash == goal)
{
wins = wins + 1;
}
}
System.out.println(100 * wins / T + "% wins");
System.out.println("Avg # bets: " + bets/T);
program_time.stop();
System.out.println(program_time.elapsedTime());
}
}
有什么想法吗?