Beginning Pseudocode:
Pseudocode is just like writing out what you want your computer program to do. A simple program (flipping a coin, for example) might look something like this:
- Print the title on the screen (“Heads or Tails Game”)
- Ask the user, “Heads or Tails?”
- Flip the coin (get a random number -- either 0 or 1 with 0 being heads)
- Tell the user what the toss was
- Tell the user “You win!” or “You lose!”
- Say “Thank you for playing!”
Now, where would you put extra instructions that asked, “Do you want to play again?” What about adding a score counter? What if you wanted to display a picture of a Head or Tail? Pseudocode is really that easy.
Looking at Programming:
class Toss {
public final int HEADS = 0;
static int countH = 0;
static int countT = 0;
static int counter = 0;
private static int face;
public static void flip() {
face = (int) (Math.random() * 2);
}
public String toString() {
String faceName;
counter++;
if (face == HEADS) {
faceName = "Heads";
countH++;
} else {
faceName = "Tails";
countT++;
}
return faceName;
}
public static void main(String[] args) {
System.out.println("Outcomes:");
do {
flip();
System.out.println(new Toss().toString());
} while (counter < 100);
System.out.println("Number of Tails: " + countT);
System.out.println("Number of Heads: " + countH);
}
}
No comments:
Post a Comment