2011-10-23 42 views
-3

我想這樣做,如果 輸入*乘兩位數, 如果輸入/劃分兩個數字 等進行加減符號。如何在Java中爲特殊字符生成if語句?

+1

你有什麼試過,到目前爲止你有什麼?另請參見:http://stackoverflow.com/questions/7828232 –

+0

可能的重複[簡單的Java遞歸下降解析庫與佔位符](http://stackoverflow.com/questions/7828232/simple-java-recursive-descent-parsing -library-with-placeholders) –

回答

1
if(input.equals("*")) // do multiplication 
else if(input.equals("/")) // do division 
else if ..... 
... 

等等...

0
if (input.equals("*")) { 
    // whatever 
} else if (input.equals("/")) { 
    // whatever 
} // etc. 

如果輸入一個字符,你可以使用一個switch聲明。

switch (input) { 
case '*': 
    // whatever 
    break; // That's important. 
case '/': 
    // whatever 
    break; 
default: 
    // handle unexpected input 
    break; 
} 

有一噸的這種方式可以實現,包括那裏的輸入字符/字符串的哈希命令處理程序的活動模式,那麼你就可以避開大的條件語句一起。或者你可以構建一個真正的解析器,並在解析器DSL中定義這種行爲。

+1

@OP還注意到,在java 7中,你可以傳遞String作爲參數來切換語句 –

+0

@ Eng.Fouad好點。 –

1

下面的方法可以幫你:

public String calculate(int input1, String operator, int input2) throws RuntimeException{ 

      String result = ""; 

      if(operator.equals("*")) { 
        result = "" + (input1 * input2); 
      } 
      else if(operator.equals("/")) { 
        try{ 
         result = "" + (input1/input2); 
        } 
        catch(DividedByZeroException e) { 
        e.printStacktrace(); 
        } 
      } 
      else if(operator.equals("-")) { 
      result = "" + (input1 - input2); 
       } 
      else if(operator.equals("+")) { 
      result = "" + (input1 + input2); 
       } 
       else { 
        throw new RuntimeException("Wrong method input!!!!") 
       } 
    return result; 

} 

如果第二輸入爲0分的時候,你會得到一個異常(你不能除以零),所以你需要處理,不知怎的。

0

我會去面向對象的方式。定義一個Operator接口,這樣的事情:

public interface Operator{ 
    int process(int left, int right); 
} 

創建這個界面的實現,並把它們放入一個地圖,關鍵是運營商的象徵。

現在使用的地圖在你的方法是這樣的:

public int process(int left, int right, String operator){ 
    return operatorMap.get(operator).process(left, right); 
} 

(如果int是不夠精確的滿足您的需求,使用不同類型的)

0

一個奇怪的很多答案。試試這個:

char operator; 
switch (operator) 
{ 
case '+': 
    // ... 
    break; 
case '-': 
    // ... 
    break; 
case '*': 
    // ... 
    break; 
case '/': 
    // ... 
    break; 
// etc 
}