[英]How to use bit-wise operators using methods in java?
我有这份作业,必须在方法中使用按位运算符。 我需要为每个运算符使用方法。 我需要使用接口BitOperators。 我无需使用方法就可以做到这一点,但是使用方法是我所必需的。 这是我所拥有的,但不起作用。 我对方法还很陌生,所以我不确定该怎么做。
import java.util.Scanner;
public class TestBitOperators {
public static interface BitOperators {
BitOperators and(byte a, byte b);
BitOperators or(byte a, byte b);
BitOperators xor(byte a, byte b);
BitOperators shift(byte n, byte l, byte r);
BitOperators comp(byte n);
}
static int and;
static int or;
static int xor;
public static void main(String[] args) {
byte a;
byte b;
byte l;
byte r;
final byte EXIT = -1;
Scanner stdin = new Scanner(System.in);
do{
System.out.println("Enter a and b numbers in the "
+ "interval [-128,127] (-1 -1 to exit): ");
a = stdin.nextByte();
b = stdin.nextByte();
}
if(a == EXIT && b == EXIT){
break;
}
System.out.println("Enter #left-shift bits in the interval [0,8]: ");
l = stdin.nextByte();
System.out.println("Enter #right-shift bits in the interval [0,8]: ");
r = stdin.nextByte();
}
System.out.println(a + " OR " + b + " is " + and);
System.out.println(a + " OR " + b + " is " + or);
System.out.println(a + " XOR " + b + " is " + xor);
System.out.println(a + " shifted left " + a + " is " + (a << l));
System.out.println(a + " shifted right " + a + " is " + (a >> r));
System.out.println(a + " unsigned-shifted right " + a +
" is " + (a >>> r));
System.out.println(a + " COMPLEMENT " + (~a));
}
while((a < abMAX && b < abMAX) && (a > abMIN && b > abMIN));
}
public static int and(byte a, byte b){
and = a&b;
return and;
}
public static int or(byte a, byte b){
or = a|b;
return or;
}
public static int xor(byte a, byte b){
xor = a^b;
return xor;
}
}
您编写了用于执行按位运算符的正确方法,但似乎您没有使用它们:
您应该调用已创建的方法,而不是访问静态变量:
System.out.println(a + " AND " + b + " is " + and(a, b));
System.out.println(a + " OR " + b + " is " + or(a, b));
System.out.println(a + " XOR " + b + " is " + xor(a, b));
有用的链接: 按位和移位运算符
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.