gpt4 book ai didi

java - 如何在java中使用方法来使用按位运算符?

转载 作者:行者123 更新时间:2023-12-01 08:49:04 24 4
gpt4 key购买 nike

我有这个家庭作业,我必须在方法中使用按位运算符。我需要为每个运算符使用方法。给出了我需要使用的接口(interface) 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));

有用链接:Bitwise and Bit Shift Operators

关于java - 如何在java中使用方法来使用按位运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42502828/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com