I am trying to make a program for my AP Computer Science A Class. I wrote the following code that is supposed to allow a user to enter two numbers and then have them guess a number inbetween that number range.
So far, it works 90% of the time, but once in a while it enters numbers either higher or lower than the set number range.
Can somebody help me figure out how to fix this problem?
Thank you.
import java.util.Scanner;
public class GuessingGameV1
{
public static void main(String[] args)
{
int rNum = 0;
int counter = 0;
int guess = 0;
Scanner in = new Scanner(System.in);
System.out.print("Choose the first number in the range: ");
int firstNumber = in.nextInt();
System.out.print("Choose the last number in the range: ");
int lastNumber = in.nextInt();
for(int i=firstNumber; i < lastNumber; i++ ){
rNum = (int)(Math.random()*lastNumber);
}
while (guess != rNum)
{
System.out.print("Enter your guess: ");
guess = in.nextInt();
if( rNum < guess )
{
counter ++;
System.out.println("Guess too high.");
}
else if( rNum == guess )
{
System.out.println("You're right!");
System.out.println("It took you " + counter + " guesses!");
}
else
{
counter ++;
System.out.println("Guess too low.");
}
}
}
}