2016-06-12 3 views
0

변수에 비트 단위 연산자를 할당하려고합니다. 내가 어떻게 해?자바의 변수에 비트 연산자를 할당하십시오.

String bitOp=""; 

     String rFunction=JOptionPane.showInputDialog(null,"Enter Your round function","Round function",JOptionPane.INFORMATION_MESSAGE); 

     if(rFunction.toUpperCase()=="AND") 
      bitOp="&"; 
     if(rFunction.toUpperCase()=="OR") 
      bitOp="|"; 
     if(rFunction.toUpperCase()=="XOR") 
      bitOp="^"; 

    int res= x +bitOp+ y; // if the operator is "AND" , this should be x & y. 
          //Here NumberFormatException error shows. 
    System.out.print(res); 

그러나 그것은 작동하지 않습니다. 누구나 제발!

+1

당신은 본질적으로

어쨌든 나는 두 번째 옵션을 선택한 것 "평가판"을하려고합니다. [this] (http://stackoverflow.com/questions/2605032/is-there-an-eval-function-in-java)를보십시오. – intboolstring

+1

또한 계산을 수행해야합니다 ("bitOp"를 지정하지 않아야 함). –

+0

열정과 같은 냄새가납니다. – chrylis

답변

1

코드를 컴파일해서는 안되므로 실제로 달성하고자하는 것이 확실하지 않습니다. 당신이 만든 문자열 표현을 평가하고 싶습니까, 아니면 좀 더 고전적으로 결과를 얻고 싶습니까? x와 y는 어디에서 왔는가 ...? 코드에서 중요한 부분이 있습니다.

int eval; 

String rFunction=JOptionPane.showInputDialog(null,"Enter Your round function","Round function",JOptionPane.INFORMATION_MESSAGE).toUpperCase(); 

if(rFunction.equals("AND")){ 
    eval = x & y; 
} else if(rFunction.equals("OR")){ 
    eval = x | y; 
} else if(rFunction.equals("XOR")){ 
    eval = x^y; 
} else { 
    //here you could also throw an exception 
    //or loop and request the user to renew their choice 
    System.out.print("Invalid choice"); 
    return; 
} 

System.out.print(res); 
2

당신은 당신의 자신의 BitOperator 만들 수 : (일부 예외 처리를 추가)

public enum BitOperator { 
    AND { 
     @Override 
     public int calc(int x, int y) { 
      return x & y; 
     } 
    }, 
    OR { 
     @Override 
     public int calc(int x, int y) { 
      return x | y; 
     } 
    }, 
    XOR { 
     @Override 
     public int calc(int x, int y) { 
      return x^y; 
     } 
    }; 

    public abstract int calc(int x,int y); 

} 

사용법 :

  String rFunction=JOptionPane.showInputDialog(null,"Enter Your round function","Round function",JOptionPane.INFORMATION_MESSAGE); 
      System.out.println(BitOperator.valueOf(rFunction.toUpperCase()).calc(x, y)); 
관련 문제