int a = keyboard.nextInt();
int b = keyboard.nextInt();
while(x < -50 || x > 50 && y < -50 || y > 50)
{
System.out.println("Error " + a + " is out of range");
System.out.println("Error " + b + " is out of range");
System.out.println();
System.out.print("Input two integers in the range [-50, + 50]: ");
a = keyboard.nextInt();
b = keyboard.nextInt();
}
while( x < -50 || x > 50)
{
System.out.println("Error " + a + " is out of range");
System.out.println();
System.out.print("Input two integers in the range [-50, + 50]: ");
a = keyboard.nextInt();
b = keyboard.nextInt();
}
while( y < -50 || y > 50)
{
System.out.println("Error " + b + " is out of range");
System.out.println();
System.out.print("Input two integers in the range [-50, + 50]: ");
a = keyboard.nextInt();
b = keyboard.nextInt();
}
我的问题是,用户输入需要是&amp; b来自[-50,50]
但是当我输入-100和100时,我只得到a超出范围或b超出范围而不是两者。
Input: a= -100 b = 100
Output:
System.out.println("Error " + -100 + " is out of range"); // CORRECT
System.out.println("Error " + 23 + " is out of range"); // ? INCORRECT
我做错了什么
答案 0 :(得分:0)
使用绝对值,请记住 |a| < x means -x < a < x
因此 a 和 b 必须符合条件或其他方式,只要**a > 50**
或**b > 50**
int a = -100;
int b = -100;
Scanner scan = new Scanner(System.in);
while (Math.abs(a) > 50 || Math.abs(b) > 50) {
System.out.println("need a:");
a = scan.nextInt();
System.out.println("need b:");
b = scan.nextInt();
}
scan.close();
System.out.println("am gone!");
答案 1 :(得分:0)
检查while循环。
while( x <= -50 || x >= 50 && y <= -50 || y > 50)
两个条件都必须为true才能成功执行。检查&&
答案 2 :(得分:0)
你对运营商的优先权感到顽皮。
x <= -50 || x >= 50 && y <= -50 || y > 50
评估为
x <= -50 || (x >= 50 && y <= -50) || y > 50
你需要加上一些括号:
(x <= -50 || x >= 50) && (y <= -50 || y > 50)
另外,请检查a
,b
,x
和y
之间的确切关系。为什么要分配到a
和b
,然后立即测试x
和y
?
答案 3 :(得分:0)
正如评论中所解释的那样,您正在测试x和y,但是阅读a和b。
此外,您的代码可以简化:
boolean valid = true;
do {
System.out.print("Input two integers in the range [-50, + 50]: ");
int a = keyboard.nextInt();
int b = keyboard.nextInt();
if ( (a < -50) || (a > 50) ) {
valid = false;
System.out.println("Error " + a + " is out of range");
}
if ( (b < -50) || (b > 50) ) {
valid = false;
System.out.println("Error " + b + " is out of range");
}
} while (!valid);
答案 4 :(得分:0)
while( x <= -50 || x >= 50 && y <= -50 || y > 50)
Java使用逻辑运算符的“短路评估”。因此,如果x = -100且y = 0,则将输入循环,因为-100 <= -50且没有其他条件,因为true || anything
始终为真。使用括号控制逻辑操作的处理方式。我建议将控制while循环的布尔条件放入一个名称很好的方法中。
private boolean bothParamsAreOutOfRange(int x, int y) {
boolean rtn = false;
if ((x <= -50 || x >= 50) && (y <= -50 || y > 50)) {
rtn = true;
}
return rtn;
}
while(bothParamsAreOutOfRange(x, y)) {
... as before ...
}