My “If” statement aren’t giving me the write answer, for example if I input “5” it prints too high which mean the random number is lower but if i input a lower number like “4” it prints too low which would mean the random number is higher. Its pretty confusing, Am just wonder if my logic in the code is correct??
import java.util.Scanner;
import java.lang.Math;
public class GuessTest
{
public static void main(String[] args)
{
System.out.println("Welcome to the gussing game, Try to guess the number am thinking of to win!");
System.out.println("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
System.out.println();
System.out.println("Am thinking of a number between 0 and 10. Try to guess it.");
System.out.println();
Scanner sc = new Scanner(System.in);
String choice = "y";
while (!choice.equalsIgnoreCase("n"))
{
System.out.println("Enter the Number:");
int guess = sc.nextInt();
double rightNum = Math.random() *10;
int randomNum = (int) rightNum;
if (guess == randomNum)
{
System.out.println("Correct you've got it! The Number Was " + randomNum );
System.out.println();
System.out.println("Would you like to play again (y/n):");
choice = sc.next();
}
else if (guess < randomNum)
{
System.out.println("your too low!");
}
else if (guess > randomNum)
{
System.out.println("Your too high!");
}
}
}
}
You’re calculating the random number on each
while-loopiteration. Just calculate it once by moving the calculation code out of the loop:Since you want to have several game rounds, you can recalculate the random number when accepting a new game: