Advertisement
mmayoub

Loops - execise no 06 slide no 68

Jun 27th, 2017
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.47 KB | None | 0 0
  1. package class170629;
  2.  
  3. import java.util.Random;
  4. import java.util.Scanner;
  5.  
  6. public class LoopsEx06Slide68 {
  7.  
  8.     public static void main(String[] args) {
  9.         // guess game
  10.         // computer select a number from 1 to 100
  11.         // player try to guess and get a feedback every time
  12.         // at the end: display number of guesses
  13.  
  14.         // computer select a secret number
  15.         Random rnd = new Random();
  16.         // create a scanner
  17.         Scanner s = new Scanner(System.in);
  18.         char yesNo; // play again: y=yes , n=no
  19.  
  20.         do {
  21.             int secret = 1 + rnd.nextInt(100); // calculated: the secret number
  22.  
  23.             // ask for and get a guess from the user
  24.             System.out.print("Enter your guess: ");
  25.             int guess = s.nextInt(); // the number from the user
  26.             int counter = 1; // number of guesses
  27.  
  28.             while (guess != secret) {
  29.                 System.out.printf("the secret number is %s than %d\n",
  30.                         guess < secret ? "greater" : "lower", guess);
  31.  
  32.                 // ask for and get the next guess from the user
  33.                 System.out.print("Enter your guess: ");
  34.                 guess = s.nextInt(); // the number from the user
  35.  
  36.                 // update counter of guesses
  37.                 counter += 1;
  38.             }
  39.  
  40.             System.out
  41.                     .printf("Great! you discoverd my secret number (%d) in %d attempts.",
  42.                             secret, counter);
  43.  
  44.             System.out.println();
  45.  
  46.             // asking for another game
  47.             System.out.print("Whould you like to play again (y / n)");
  48.             yesNo = s.next().charAt(0);
  49.  
  50.         } while (yesNo == 'y');
  51.  
  52.         System.out.println("\nQuiting the game ...\nBye");
  53.         s.close();
  54.     }
  55.  
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement