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

标签 java methods

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

相关文章:

c++ - 什么是非静态成员函数?

C++编译问题;类方法

java - 驱动程序和方法不工作

java - new Foo(bar) {public void baz(){....} }; 是什么意思?在Java中是什么意思?

java - 如何从 Netbeans Navigator 窗口中删除 getter 和 setter

java - 如何使用二维数组创建矩阵

java - Joda-Time 忽略 en-US 服务器上的语言环境

java - 在java中,如何创建一个根据以前的方法对对象进行分类的方法?

java - Spring Batch JUnit 测试未加载 JobLauncherTestUtils 的 application.properties

java - 使用凭据缓存的 Kerberos 身份验证通过 Eclipse 工作,但不能通过命令行工作