Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package it.miodominio.corso;
- import java.util.Random;
- import java.util.Scanner;
- public class GuessTheNumber {
- static int random() {
- return new Random().nextInt(1000) + 1;
- }
- static int readNumber() {
- Scanner s = new Scanner(System.in);
- return Integer.parseInt(s.nextLine());
- }
- public static void main(String[] args) {
- /*
- * Il computer "pensa" ad un numero compreso tra 1 e 1000 (random)
- * L'utente ha 10 tentativi per indovinarlo sulla base delle indicazioni
- * fornite dal programma. Esempio: Indovina: 500 Il numero al quale ho
- * pensato è più grande Indovina: 700 Il numero al quale ho pensato è
- * più piccolo Indovina: 600 Hai indovinatop
- */
- // il computer pensa ad un numero casuale
- int target = random(); System.out.println(target);
- // devo contare il numero di tentativi effettuati finora
- int attempts = 0;
- // variabile di appoggio per sapere se l'utente ha vinto
- boolean won = false;
- // l'utente ha a disposizione 10 tentativi per vincere!
- while (attempts < 10 && !won) {
- ++attempts; // incremento il numero di tentativi
- // leggo il numero da tastiera
- System.out.print("Tentativo n. " + attempts + ". Scrivi il numero: ");
- int answer = readNumber();
- // controllo la risposta
- if (answer < target)
- System.out.println("Troppo piccolo");
- else if (answer > target)
- System.out.println("Troppo grande");
- else
- won = true;
- }
- // il gioco è terminato: controllo se l'utente ha vinto
- if (won)
- System.out.println("Bravo, hai indovinato in " + attempts + " tentativi.");
- else
- System.out.println("Hai perso, il numero era " + target);
- }
- }
Add Comment
Please, Sign In to add comment