[英]Can't get results from boolean to appear correctly
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.
Boolean 结果 = true 存在,因为如果不是,则会出现“找不到符号”错误。
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:您的
displayGuessResult
应该改进:
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
来调用它:
input = getValidGuess(scan);
displayGuessResults(input);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.