Advertisement
NelloRizzo

Guess The Number

Nov 27th, 2018
351
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.50 KB | None | 0 0
  1. package corso.java;
  2.  
  3. import java.util.Random;
  4. import java.util.Scanner;
  5.  
  6. public class Program {
  7.  
  8.     static int thinkNumber() {
  9.         return new Random().nextInt(1000) + 1;
  10.     }
  11.  
  12.     static int readNumberFromConsole() {
  13.         System.out.print("Scrivi un numero: ");
  14.         return new Scanner(System.in).nextInt();
  15.     }
  16.  
  17.     public static void main(String[] args) {
  18.         // numero casuale tra 1 e 1000
  19.         int target = thinkNumber();
  20.         // SOLO PER TEST MI STAMPO IL NUMERO DA INDOVINARE
  21.         System.out.println(target);
  22.         // numero di tentativi effettuati
  23.         int attempts = 0;
  24.         // variabile per leggere l'input utente
  25.         int number;
  26.         // inizio ciclo
  27.         do {
  28.             // stampo il numero di tentativi effettuati finora
  29.             System.out.print("Hai effettuato " + attempts + " tentativi. ");
  30.             // leggo il numero da tastiera
  31.             number = readNumberFromConsole();
  32.             // numero < target ?
  33.             if (number < target)
  34.             // si
  35.             {
  36.                 System.out.println("Il numero è più piccolo.");
  37.             } else
  38.             // no
  39.             {
  40.                 // numero > target ?
  41.                 if (number > target)
  42.                 // si
  43.                 {
  44.                     System.out.println("Il numero è più grande.");
  45.                 } else
  46.                 // no
  47.                 {
  48.                     System.out.println("Bravo, hai indovinato.");
  49.                 }
  50.             }
  51.             // incremento i tentativi
  52.             ++attempts;
  53.         }
  54.         // il ciclo continua fino ad esaurire i tentativi
  55.         // oppure fino a quando numero == target
  56.         while (attempts < 10 && number != target);
  57.         // controllo se ha perso
  58.         if (number != target)
  59.             System.out.println("Hai perso, il numero era " + target);
  60.     }
  61.  
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement