NelloRizzo

GuessTheNumber

May 22nd, 2017
318
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.66 KB | None | 0 0
  1. package it.miodominio.corso;
  2.  
  3. import java.util.Random;
  4. import java.util.Scanner;
  5.  
  6. public class GuessTheNumber {
  7.  
  8.     static int random() {
  9.         return new Random().nextInt(1000) + 1;
  10.     }
  11.  
  12.     static int readNumber() {
  13.         Scanner s = new Scanner(System.in);
  14.         return Integer.parseInt(s.nextLine());
  15.     }
  16.  
  17.     public static void main(String[] args) {
  18.         /*
  19.          * Il computer "pensa" ad un numero compreso tra 1 e 1000 (random)
  20.          * L'utente ha 10 tentativi per indovinarlo sulla base delle indicazioni
  21.          * fornite dal programma. Esempio: Indovina: 500 Il numero al quale ho
  22.          * pensato è più grande Indovina: 700 Il numero al quale ho pensato è
  23.          * più piccolo Indovina: 600 Hai indovinatop
  24.          */
  25.  
  26.         // il computer pensa ad un numero casuale
  27.         int target = random(); System.out.println(target);
  28.         // devo contare il numero di tentativi effettuati finora
  29.         int attempts = 0;
  30.         // variabile di appoggio per sapere se l'utente ha vinto
  31.         boolean won = false;
  32.         // l'utente ha a disposizione 10 tentativi per vincere!
  33.         while (attempts < 10 && !won) {
  34.             ++attempts; // incremento il numero di tentativi
  35.             // leggo il numero da tastiera
  36.             System.out.print("Tentativo n. " + attempts + ". Scrivi il numero: ");
  37.             int answer = readNumber();
  38.             // controllo la risposta
  39.             if (answer < target)
  40.                 System.out.println("Troppo piccolo");
  41.             else if (answer > target)
  42.                 System.out.println("Troppo grande");
  43.             else
  44.                 won = true;
  45.         }
  46.         // il gioco è terminato: controllo se l'utente ha vinto
  47.         if (won)
  48.             System.out.println("Bravo, hai indovinato in " + attempts + " tentativi.");
  49.         else
  50.             System.out.println("Hai perso, il numero era " + target);
  51.     }
  52.  
  53. }
Add Comment
Please, Sign In to add comment