Advertisement
Guest User

Untitled

a guest
May 27th, 2019
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.97 KB | None | 0 0
  1. /**
  2. * Kalkulator
  3. */
  4. import java.util.Scanner;
  5.  
  6. public class Kalkulator {
  7.  
  8. public static boolean isNumeric(String str) {
  9. try {
  10. Integer.parseInt(str);
  11. return true;
  12. } catch (NumberFormatException e) {
  13. return false;
  14. }
  15. }
  16.  
  17. public static boolean isOperator(String str) {
  18. if ((str.equals("+")) || (str.equals("-")) || (str.equals("*")) || (str.equals("/")) || (str.equals("%"))
  19. || (str.equals("^")))
  20. return true;
  21. return false;
  22. }
  23.  
  24. public static void main(String[] args) {
  25.  
  26. boolean t1 = false;
  27. boolean t2 = false;
  28. boolean t3 = false;
  29. String n1, n2, n3;
  30. int h1 = 0;
  31. int h2 = 0;
  32. String h3 = "";
  33. float val1, val2, val3;
  34. Scanner scan = new Scanner(System.in);
  35. while (!t1) {
  36. System.out.print("Nilai-1 = ");
  37. n1 = scan.nextLine();
  38. if (isNumeric(n1)) {
  39. h1 = Integer.parseInt(n1);
  40. t1 = true;
  41. }
  42. }
  43.  
  44. while (!t2) {
  45. System.out.print("Nilai-2 = ");
  46. n2 = scan.nextLine();
  47. if (isNumeric(n2)) {
  48. h2 = Integer.parseInt(n2);
  49. t2 = true;
  50. }
  51. }
  52.  
  53. while (!t3) {
  54. System.out.print("Operator [+, -, *, /, %, ^] = ");
  55. n3 = scan.nextLine();
  56. if (isOperator(n3)) {
  57. h3 = n3;
  58. t3 = true;
  59. }
  60. }
  61. switch (h3) {
  62. case "+":
  63. val1 = (float) h1;
  64. val2 = (float) h2;
  65. val3 = val1 + val2;
  66. System.out.printf("Hasil: %,.2f + %,.2f = %,.2f", val1, val2, val3);
  67. break;
  68. case "-":
  69. val1 = (float) h1;
  70. val2 = (float) h2;
  71. val3 = val1 - val2;
  72. System.out.printf("Hasil: %,.2f - %,.2f = %,.2f", val1, val2, val3);
  73. break;
  74. case "*":
  75. val1 = (float) h1;
  76. val2 = (float) h2;
  77. val3 = val1 * val2;
  78. System.out.printf("Hasil: %,.2f * %,.2f = %,.2f", val1, val2, val3);
  79. break;
  80. case "/":
  81. val1 = (float) h1;
  82. val2 = (float) h2;
  83. val3 = val1 / val2;
  84. System.out.printf("Hasil: %,.2f / %,.2f = %,.2f", val1, val2, val3);
  85. break;
  86. case "^":
  87. val1 = (float) h1;
  88. val2 = (float) h2;
  89. val3 = (float) Math.pow((double) val1, (double) val2);
  90. System.out.printf("Hasil: %,.2f ^ %,.2f = %,.2f", val1, val2, val3);
  91. break;
  92. case "%":
  93. val1 = (float) h1;
  94. val2 = (float) h2;
  95. val3 = val1 % val2;
  96. System.out.printf("Hasil: %,.2f % %,.2f = %,.2f", val1, val2, val3);
  97. break;
  98. default:
  99. break;
  100. }
  101. scan.close();
  102. }
  103. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement