CSE142 Sample Program handout #13
Sample Log of Execution
-----------------------
This program plays a guessing game with you.
I'm thinking of a number between 1 and 10.
Your guess? 5
Your guess? 3
Your guess? 7
Your guess? 9
Your guess? 2
Your guess? 1
Your guess? 8
Your guess? 4
Your guess? 10
Your guess? 6
You got it right in 10 guesses
Another Sample Log of Execution
-------------------------------
This program plays a guessing game with you.
I'm thinking of a number between 1 and 10.
Your guess? 8
Your guess? 6
Your guess? 2
You got it right in 3 guesses
Program File SimpleGuess.java
-----------------------------
// Stuart Reges
// 10/25/04
//
// This program plays a simple guessing game with the user.
import java.util.*;
public class SimpleGuess {
public static void main(String[] args) {
giveIntro();
Scanner console = new Scanner(System.in);
Random r = new Random();
int guesses = 0;
int number = r.nextInt(10) + 1;
int guess = -1;
while (guess != number) {
guesses++;
System.out.print("Your guess? ");
guess = console.nextInt();
}
System.out.println();
System.out.println("You got it right in " + guesses + " guesses");
}
// explains the program to the user
public static void giveIntro() {
System.out.println("This program plays a guessing game with you.");
System.out.println("I'm thinking of a number between 1 and 10.");
System.out.println();
}
}