我编写了一个无法作为Java Applet运行的简单程序。当我尝试运行程序时,会弹出一个框架并询问要运行哪个程序。我点击了我写的程序,如下所示。令人惊讶的是,Eclipse会在同一个默认包中运行其他程序。谁能告诉我出了什么问题?
以下是Java的艺术与科学第6章练习3中的一个程序:
import acm.util.*;
public class ApproxPIValue {
public void run() {
int total = 0; //This variable counts the amount of time x^2 + y^2 < 1.//
for (int a = 0; a < 10000; a++) {
double x = rgen.nextDouble(-1.0, 1.0);
double y = rgen.nextDouble(-1.0, 1.0);
if (Math.sqrt(x) + Math.sqrt(y) < 1) { //x^2 + y^2 < 1 means that this pair number will fall into the circle with radius of 1 centered in the middle of the coordinates.
total++;
}
double approxPIValue = total / 10000 * 4; //total / 100000 is the approximate ratio of the area of the circle over the area of the square. The approximate ratio would be close to PI/4 if x and y are randomly chosen. So total / 10000 * 4 will give the approximate PI.//
System.out.print(approxPIValue);
}
}
/* set RandomGenerator as an instance variable. */
private RandomGenerator rgen = new RandomGenerator();
}
我还想提出另一个无效的程序。
import acm.util.*;
/**
* This class decides the face of a coin.
* 1 and 2 represent correspondingly Heads and Tails.
* Clients can get the "face" of the coin by calling getState() method.
*/
public class CoinFace {
public CoinFace() {
state = rgen.nextInt(1, 2);
}
/* private instance variable. */
private int state;
public int getState() {
return state;
}
/* declare RandomGenerator as an instance variable. */
private RandomGenerator rgen = new RandomGenerator();
}
public class ConsecutiveHeads extends CoinFace{
public void run () {
while (true) {
int totalFlip = 0;
int consecutiveHeads = 0; //the time of getting consecutive Heads when flipping a coin.//
CoinFace a = new CoinFace();
if (a.getState() == 1) {
System.out.print("Heads");
totalFlip++;
consecutiveHeads++;
} else if (consecutiveHeads == 3) {
System.out.print("It took " + totalFlip + " to get 3 consecutive heads." );
break;
} else {
System.out.print("Tails");
consecutiveHeads = 0;
totalFlip++;
}
}
}
}
由于我无法运行程序,我不知道程序会如何运行。提前感谢有关改进计划的任何解决方案和建议!
答案 0 :(得分:2)
ACM JApplet
显然被称为Program
。一个应用程序如果要嵌入网页,则必须扩展Program
。
但为什么要编写applet?如果是由于规格。请教老师,请参阅Why CS teachers should stop teaching Java applets。