2017-02-28 68 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