Reputation: 1
I wrote a simple program that couldn't be run as a Java Applet. When I tried to run the program, a frame did pop up and and asked which program to be run. I clicked the program I wrote, which is shown below. Surprisingly, Eclipse would run other programs in the same default package. Can anyone tell me what went wrong?
Here is one program from The Art and Science of Java Chapter 6 Exercise 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();
}
I also want to pose another program that doesn't work either.
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++;
}
}
}
}
Since I couldn't run the program, I don't know how the programs would turn out. Thanks in advance for any solution and advice on improving the programs!
Upvotes: 0
Views: 215
Reputation: 168845
The ACM JApplet
is apparently called a Program
. An app. must extend Program
if it is to be embedded in a web page.
But why code an applet? If it is due to spec. by teacher, please refer them to Why CS teachers should stop teaching Java applets.
Upvotes: 2