Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package class170629;
- import java.util.Random;
- import java.util.Scanner;
- public class LoopsEx06Slide68 {
- public static void main(String[] args) {
- // guess game
- // computer select a number from 1 to 100
- // player try to guess and get a feedback every time
- // at the end: display number of guesses
- // computer select a secret number
- Random rnd = new Random();
- // create a scanner
- Scanner s = new Scanner(System.in);
- char yesNo; // play again: y=yes , n=no
- do {
- int secret = 1 + rnd.nextInt(100); // calculated: the secret number
- // ask for and get a guess from the user
- System.out.print("Enter your guess: ");
- int guess = s.nextInt(); // the number from the user
- int counter = 1; // number of guesses
- while (guess != secret) {
- System.out.printf("the secret number is %s than %d\n",
- guess < secret ? "greater" : "lower", guess);
- // ask for and get the next guess from the user
- System.out.print("Enter your guess: ");
- guess = s.nextInt(); // the number from the user
- // update counter of guesses
- counter += 1;
- }
- System.out
- .printf("Great! you discoverd my secret number (%d) in %d attempts.",
- secret, counter);
- System.out.println();
- // asking for another game
- System.out.print("Whould you like to play again (y / n)");
- yesNo = s.next().charAt(0);
- } while (yesNo == 'y');
- System.out.println("\nQuiting the game ...\nBye");
- s.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement