Sunday, July 16, 2017

Write a guess number game.

/**
 * Created by Jo on 7/10/2017.
 * For more exercises and lessons, visit http://shegertech.blogspot.com/
 */

import java.util.Random;
import java.util.Scanner;

public class Q2Solution {
    public static void main(String[] args){

        System.out.println("Pick a number: ");

        Scanner inputnum = new Scanner(System.in);
        int maxnum;
        maxnum = inputnum.nextInt();

        Random rand = new Random();
        int number = rand.nextInt(maxnum);
        int tries = 0;
        Scanner input = new Scanner(System.in);
        int guess;
        boolean win = false;

        while (win == false){

            System.out.println("Guess a number between 1 and "+ maxnum +": ");
            guess = input.nextInt();
            tries++;

            if (guess == number){
                win = true;
               
            }

            else if(guess < number){
                System.out.println("Number is to low, tray again");
               
            }

            else if(guess > number){
                System.out.println("Number is to high, try again");
               
            }

        }

        System.out.println("You win!");
        System.out.println("It took you "+ tries + " tries.");

    }
}

Share: