提问人:b3jf 提问时间:10/26/2022 更新时间:10/26/2022 访问量:88
'NOT' 运算符 (!) 在与 Java 中的方法一起使用时如何工作?[关闭]
How the 'NOT' operator(!) works when used with methods in Java? [closed]
问:
以下是使用访问修饰符来避免生成异常的示例:
class FailSoftArray {
private int a[];
private int errval;
public int length;
public FailSoftArray(int size, int errv) {
a = new int[size];
errval = errv;
length = size;
}
public int get(int index) {
if(indexOK(index)) return a[index];
return errval;
}
public boolean put(int index, int val) {
if(indexOK(index)) {
a[index] = val;
return true;
}
return false;
}
private boolean indexOK(int index) {
if(index >= 0 & index < length) return true;
return false;
}
}
public class TestMethod {
public static void main(String[] args) {
FailSoftArray333 fs = new FailSoftArray(5, -1);
int x;
System.out.println("\nError access message.");
for(int i = 0; i < (fs.length * 2); i++)
if(!fs.put(i, i*10))
System.out.println("Index " + i + " outside the range of the array");
for(int i =0; i < (fs.length * 2); i++) {
x = fs.get(i);
if(x != -1) System.out.print(x + " ");
else
System.out.println("Index " + i + " outside the range of the array");
}
}
}
我不明白为什么在这种情况下我必须使用运算符 (!) 才能使代码正常工作:
System.out.println("\nError access message.");
for(int i = 0; i < (fs.length * 2); i++)
if(!fs.put(i, i*10))
System.out.println("Index " + i + " outside the range of the array");
当我用 (!) 打印它时,结果是你所期望的:
Error access message..
Index 5 outside the range of the array
Index 6 outside the range of the array
Index 7 outside the range of the array
Index 8 outside the range of the array
Index 9 outside the range of the array
0 10 20 30 40 Index 5 outside the range of the array
Index 6 outside the range of the array
Index 7 outside the range of the array
Index 8 outside the range of the array
Index 9 outside the range of the array
没有 (!):
Error access message..
Index 0 outside the range of the array
Index 1 outside the range of the array
Index 2 outside the range of the array
Index 3 outside the range of the array
Index 4 outside the range of the array
0 10 20 30 40 Index 5 outside the range of the array
Index 6 outside the range of the array
Index 7 outside the range of the array
Index 8 outside the range of the array
Index 9 outside the range of the array
有人可以向我解释在这种情况下运算符 (!) 究竟是如何工作的吗?为什么需要它,它如何影响方法?
答:
0赞
mmartinez04
10/26/2022
#1
函数返回一个值/它是否能够成功地在数组中的索引处获得新值put
FailSoftArray
boolean
true
false
put
val
index
a
表示逻辑!
NOT
通过使用 ,您实际上是在告诉编译器if(!fs.put(i, i*10))
if(put was NOT able to place i*10 at index i)
System.out.println("Index " + i + " outside the range of the array");
省略就像说!
if(put succeeded)
//Print error
这显然不是故意的
上一个:一元是否将变量设置为其初始值
评论
boolean
put
boolean
put
返回一个布尔值。如果索引不正常(基于 ),则该方法返回 false。在这些情况下,计算结果为 ,这与 相同,从而执行语句。indexOK
if(!fs.put(...))
if(!false)
if(true)
System.out.println