我想這樣做,如果 輸入「*
」乘兩位數, 如果輸入「/
」劃分兩個數字 等進行加減符號。如何在Java中爲特殊字符生成if語句?
-3
A
回答
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
}
相關問題
- 1. 如何在SSIS中生成IF語句
- 2. PDO select語句中的特殊字符
- 3. PHP中的特殊字符MySQL語句
- 4. 如何在java中爲所有特殊字符(',%,\,:,{,})轉義所有特殊字符
- 5. 如何在Hive shell/JDBC語句中轉義特殊字符?
- 6. 如何將If語句組合成一個更大的If語句在Java中
- 7. 如何在準備好的語句中使用特殊字符java
- 8. 如何聲明在java中這個字符串(IF else語句)
- 9. HAML特殊情況縮進if語句
- 10. 生成與if語句
- 11. 如何在xml文件中顯示/生成特殊字符「&」?
- 12. 在java中將if-else-if語句轉換爲switch語句
- 13. 打開字符串如果語句一個Java IF語句
- 14. 如何在if語句中使用if語句來返回字符串?
- 15. 如何在java中結束if語句?
- 16. 如何特殊字符,換句話說
- 17. java if語句字符串比較
- 18. python中if語句中的生成器
- 19. Java生成的XML以.Net/SQL中的特殊字符顯示
- 20. PHP語句中的特殊字符(如España中)?
- 21. 如何比較if語句中的多個字符串與Java?
- 22. Java中的特殊字符
- 23. Java中的特殊字符
- 24. Java - ||和&&在if語句中
- 25. 如何在Java中檢查字符串特殊字符
- 26. Java if和else if語句不生成輸出
- 27. 如何在compilejava.net中使用此代碼生成If else語句?
- 28. 如何在RecyclerView中生成if語句條件
- 29. 在if語句中比較字符串
- 30. Java - 如何將特殊字符轉換爲字符串
你有什麼試過,到目前爲止你有什麼?另請參見:http://stackoverflow.com/questions/7828232 –
可能的重複[簡單的Java遞歸下降解析庫與佔位符](http://stackoverflow.com/questions/7828232/simple-java-recursive-descent-parsing -library-with-placeholders) –