我正在创建一个程序,要求用户猜测数字。然后程序确定猜测的数字是否在两个随机数的范围内。我有一个公共(public)静态 boolean 值,即使我有返回值(在 if 和 else if 内),它也会显示错误。刚接触方法,不确定如何解决,我该如何解决这个问题?请注意,我无法创建第二个 boolean 值,两个验证都必须保留在 displayGuessResults 中,因为这是程序所需要的。另外,代码不完整,因为我还没有完成对 main 的调用,我只是想在继续之前解决这个问题,谢谢!
代码(不包括 main,因为我还没有任何内容):
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;
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)
{
System.out.println("\nThe 2 random numbers are " + start +
" and " + end);
System.out.println("Good Guess!");
return true;
}
else if (num < start || num > end)
{
System.out.println("\nThe 2 random numbers are " + start +
" and " + end);
System.out.println("Outside range.");
return false;
}
} // displayGuessResults end
最佳答案
如果 num == start || 会怎样?数==结束?你还没有考虑过它,因此对于这种情况,它不会进入 if/else if 。因此你也需要处理它
关于java - 如何修复 boolean 方法中的返回错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61380209/