Last active
October 9, 2020 13:30
-
-
Save donchan922/70fd79a3c897111cbfacb1b29d0e6139 to your computer and use it in GitHub Desktop.
コンソールを用いた簡易電卓
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.math.BigDecimal; | |
import java.math.RoundingMode; | |
public class Dentaku { | |
public static void main(String[] args) { | |
// 引数が3つであるかどうかのチェック | |
if (args.length != 3) { | |
System.out.println("引数は3つである必要があります。"); | |
return; | |
} | |
try { | |
// 引数1:1つ目の数値 | |
BigDecimal val1 = new BigDecimal(args[0]); | |
// 引数2:演算子 | |
String operand = args[1]; | |
// 引数3:2つ目の数値 | |
BigDecimal val2 = new BigDecimal(args[2]); | |
// 計算する | |
if (operand.equals("+")) { | |
System.out.println(val1.add(val2)); | |
} else if (operand.equals("-")) { | |
System.out.println(val1.subtract(val2)); | |
} else if (operand.equals("*")) { | |
System.out.println(val1.multiply(val2)); | |
} else if (operand.equals("/")) { | |
// 少数第三位を四捨五入する | |
System.out.println(val1.divide(val2, 2, RoundingMode.HALF_UP)); | |
} else { | |
System.out.println("引数2は、+, -, *, /のいずれかを入力してください。"); | |
} | |
} catch (NumberFormatException e) { | |
System.out.println("引数1と引数3は数値を入力してください。"); | |
} catch (ArithmeticException e) { | |
System.out.println("引数3は0以外で入力してください。"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment