My program asks the user for a number and then decides if the number is between the range of two randomly generated numbers or outside of it. Everything works fine, except the program keeps giving the result that the guessed number is outside the range, even when it is inside the range. Not sure how to get the answer to show correctly. Boolean result = true is there since a "Cannot find symbol" error appears if it is not.
Code:
public static int getValidGuess(Scanner get)
{
int num;
System.out.print("Guess a number: --> ");
num = get.nextInt();
return num;
} // getValidGuess end
public static boolean displayGuessResults(int start, int end, int num)
{
int n1, n2;
boolean result = true;
Random gen = new Random();
n1 = gen.nextInt(99) + 1;
n2 = gen.nextInt(99) + 1;
if(n1 < n2)
{
start = n1;
end = n2;
} // if end
else
{
start = n2;
end = n1;
} //else end
if(num > start && num < end){
result = true;
System.out.println("\nThe 2 random numbers are " + start +
" and " + end);
System.out.println("Good Guess!");
} //if end
if(num < start || num > end){
result = false;
System.out.println("\nThe 2 random numbers are " + start +
" and " + end);
System.out.println("Outside range.");
} //if end
return result;
} // displayGuessResults end
public static void main(String[] args) {
// start code here
int start = 0, end = 0, num = 0, input;
Scanner scan = new Scanner(System.in);
String doAgain = "Yes";
while (doAgain.equalsIgnoreCase("YES")) {
// call method
input = getValidGuess(scan);
displayGuessResults(start, end, num);
System.out.print("\nEnter YES to repeat --> ");
doAgain = scan.next();
} //end while loop
} //main end
Your displayGuessResult
should be improved:
public static boolean displayGuessResults(int num) {
boolean result = true;
Random gen = new Random();
int n1 = gen.nextInt(99) + 1;
int n2 = gen.nextInt(99) + 1;
int start = Math.min(n1, n2);
int end = Math.max(n1, n2);
System.out.println("\nThe 2 random numbers are " + start + " and " + end);
if(num >= start && num <= end){
result = true;
System.out.println("Good Guess!");
} else {
result = false;
System.out.println("Outside range.");
}
return result;
} // displayGuessResults end
and you have to call it using input
read from the Scanner:
input = getValidGuess(scan);
displayGuessResults(input);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.