mardi 17 août 2021

Creating High Low game and the count down prints down to 0 in one guess and ends the game. How do I correct this so it counts down for each guess?

The game asks the user to enter the lowest possible value and the highest possible value. The computer then picks a random number between the values given. The user has a certain amount of guesses depending on the range given. The user should guess the number and if it is wrong the program should say if the guess is to high or to low and tell the user how many guesses are left. The problem is when you make one guess the counter counts down to zero with the first guess. See the code and the results bellow.

import java.util.Scanner;

public class highlow {
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        System.out.println("Lets play a game! Let me know a range, I will pick a number and 
        you guess what it is.");
        System.out.println("What is the lowest possible value? ");
        int min=sc.nextInt();
        System.out.println("What is the highest possible value? ");
        int max=sc.nextInt();
        System.out.println("Great I will think of a number between " + min + " and " + max);

        double y=Math.sqrt(max-min+1);  //Calculation for # of guesses
        double DoubleValue=y;
        int IntValue=(int) DoubleValue;     //turn double into integer 
        System.out.println("You have " + IntValue + " guesses left.");

        int correctNum=(int)Math.floor(Math.random()*(max-min+1)+min);

        int i;
        for(i=IntValue; i>=0; i--){
        System.out.println("What is your guess? ");
        int guess=sc.nextInt();
        while(i>0){
        if(guess < correctNum){
            System.out.println("number is too low! You have " + i-- + " guesses left.");
        }
        else if(guess > correctNum){
            System.out.println("Number is too high! You have " + i-- + " guesses left.");
        }
        else if(guess == correctNum){
            System.out.println("You Win! Are you smart or did you cheat?");
        }
        else{
            System.out.println("not a valid option");
        }
    }
    }
}
}

Results: Lets play a game! Let me know a range, I will pick a number and you guess what it is. What is the lowest possible value? 1 What is the highest possible value? 50 Great I will think of a number between 1 and 50 You have 7 guesses left. What is your guess? 9 number is too low! You have 7 guesses left. number is too low! You have 6 guesses left. number is too low! You have 5 guesses left. number is too low! You have 4 guesses left. number is too low! You have 3 guesses left. number is too low! You have 2 guesses left. number is too low! You have 1 guesses left.




Aucun commentaire:

Enregistrer un commentaire