Last active
April 8, 2020 09:32
-
-
Save naijab/2b724fb1bee72ed829a89abc4801e43f to your computer and use it in GitHub Desktop.
Calculate Number with operator
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.text.DecimalFormat; | |
import java.util.Scanner; | |
public class Main { | |
private static Scanner scanner; | |
public static void main(String[] args) { | |
init(); | |
doSomeThing(); | |
} | |
private static void init() { | |
scanner = new Scanner(System.in); | |
} | |
private static void doSomeThing() { | |
String number = scanner.nextLine(); | |
cutNumber(number); | |
} | |
private static void cutNumber(String number) { | |
int operator = checkOperatorPosition(number); | |
int numberA = Integer.parseInt(number.substring(0, operator)); | |
int numberB = Integer.parseInt(number.substring(operator + 1)); | |
double total = calculate(number, numberA, numberB); | |
DecimalFormat dc = new DecimalFormat("0.00"); | |
System.out.println(dc.format(total)); | |
} | |
private static int checkOperatorPosition(String number) { | |
if (number.contains("+")) { | |
return number.indexOf("+"); | |
} else if (number.contains("-")) { | |
return number.indexOf("-"); | |
} else if (number.contains("*")) { | |
return number.indexOf("*"); | |
} else if (number.contains("/")) { | |
return number.indexOf("/"); | |
} else { | |
return number.indexOf("%"); | |
} | |
} | |
private static String checkOperator(String number) { | |
if (number.contains("+")) { | |
return "+"; | |
} else if (number.contains("-")) { | |
return "-"; | |
} else if (number.contains("*")) { | |
return "*"; | |
} else if (number.contains("/")) { | |
return "/"; | |
} else { | |
return "%"; | |
} | |
} | |
private static double calculate(String number, int numberA, int numberB) { | |
double a = (double) numberA; | |
double b = (double) numberB; | |
double sum = 0; | |
switch (checkOperator(number)) { | |
case "+": | |
sum = a + b; | |
break; | |
case "-": | |
sum = a - b; | |
break; | |
case "*": | |
sum = a * b; | |
break; | |
case "/": | |
sum = a / b; | |
break; | |
case "%": | |
sum = a % b; | |
break; | |
default: | |
break; | |
} | |
return sum; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment