2017-02-28 31 views
0

我有这个家庭作业的任务,我必须使用位智者与方法。我需要为每个操作员使用方法。 BitOperators接口是我需要使用的一些参数。我能够在不使用方法的情况下做到这一点,但我需要使用方法。这是我的,但它不工作。我对方法相当陌生,所以我不知道该怎么做。如何在java中使用按位运算符?

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; 
} 
} 
+1

你似乎没有调用你的方法。你可能会做类似'System.out.println(a +“或”+ b +“是”+或(a,b));' – Berger

+1

在你的方法中,你指的是静态变量。这应该更改为局部变量,或完全消除变量。对于'和',你应该只做'return a&b;'。其他人也一样,不需要将结果存储在临时表中。 –

回答

1

你写进行位运算符正确的方法,但你不使用它们似乎:

你应该调用方法您已经创建,而不是访问静态变量:

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