Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Kalkulator
- */
- import java.util.Scanner;
- public class Kalkulator {
- public static boolean isNumeric(String str) {
- try {
- Integer.parseInt(str);
- return true;
- } catch (NumberFormatException e) {
- return false;
- }
- }
- public static boolean isOperator(String str) {
- if ((str.equals("+")) || (str.equals("-")) || (str.equals("*")) || (str.equals("/")) || (str.equals("%"))
- || (str.equals("^")))
- return true;
- return false;
- }
- public static void main(String[] args) {
- boolean t1 = false;
- boolean t2 = false;
- boolean t3 = false;
- String n1, n2, n3;
- int h1 = 0;
- int h2 = 0;
- String h3 = "";
- float val1, val2, val3;
- Scanner scan = new Scanner(System.in);
- while (!t1) {
- System.out.print("Nilai-1 = ");
- n1 = scan.nextLine();
- if (isNumeric(n1)) {
- h1 = Integer.parseInt(n1);
- t1 = true;
- }
- }
- while (!t2) {
- System.out.print("Nilai-2 = ");
- n2 = scan.nextLine();
- if (isNumeric(n2)) {
- h2 = Integer.parseInt(n2);
- t2 = true;
- }
- }
- while (!t3) {
- System.out.print("Operator [+, -, *, /, %, ^] = ");
- n3 = scan.nextLine();
- if (isOperator(n3)) {
- h3 = n3;
- t3 = true;
- }
- }
- switch (h3) {
- case "+":
- val1 = (float) h1;
- val2 = (float) h2;
- val3 = val1 + val2;
- System.out.printf("Hasil: %,.2f + %,.2f = %,.2f", val1, val2, val3);
- break;
- case "-":
- val1 = (float) h1;
- val2 = (float) h2;
- val3 = val1 - val2;
- System.out.printf("Hasil: %,.2f - %,.2f = %,.2f", val1, val2, val3);
- break;
- case "*":
- val1 = (float) h1;
- val2 = (float) h2;
- val3 = val1 * val2;
- System.out.printf("Hasil: %,.2f * %,.2f = %,.2f", val1, val2, val3);
- break;
- case "/":
- val1 = (float) h1;
- val2 = (float) h2;
- val3 = val1 / val2;
- System.out.printf("Hasil: %,.2f / %,.2f = %,.2f", val1, val2, val3);
- break;
- case "^":
- val1 = (float) h1;
- val2 = (float) h2;
- val3 = (float) Math.pow((double) val1, (double) val2);
- System.out.printf("Hasil: %,.2f ^ %,.2f = %,.2f", val1, val2, val3);
- break;
- case "%":
- val1 = (float) h1;
- val2 = (float) h2;
- val3 = val1 % val2;
- System.out.printf("Hasil: %,.2f % %,.2f = %,.2f", val1, val2, val3);
- break;
- default:
- break;
- }
- scan.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement