Skip to content

Instantly share code, notes, and snippets.

@imryan
Created January 7, 2014 17:51
Show Gist options
  • Save imryan/8303453 to your computer and use it in GitHub Desktop.
Save imryan/8303453 to your computer and use it in GitHub Desktop.
CLI calculator that performs computations on one line.
import java.text.NumberFormat;
import java.util.Locale;
import java.util.Scanner;
public class ConsoleCalc {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
scanNumbers(line);
sc.close();
}
public static int containsOperator(String line) {
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) == '+') {
return 0;
} else if (line.charAt(i) == '-') {
return 1;
} else if (line.charAt(i) == '*') {
return 2;
} else if (line.charAt(i) == '/') {
return 3;
} else if (line.charAt(i) == '^') {
return 4;
}
}
return 5;
}
public static void scanNumbers(String line) {
int a = 0;
int b = 0;
int endIndex = 0;
String tempA = "", tempB = "";
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) != ' ' && line.charAt(i) != '+' && line.charAt(i) != '-' && line.charAt(i) != '*' && line.charAt(i) != '/' && line.charAt(i) != '^') {
tempA = tempA.concat(Character.toString(line.charAt(i)));
a = Integer.parseInt(tempA);
endIndex = i;
} else {
break;
}
}
for (int ii = endIndex+1; ii < line.length(); ii++) {
if (line.charAt(ii) != ' ' && line.charAt(ii) != '+' && line.charAt(ii) != '-' && line.charAt(ii) != '*' && line.charAt(ii) != '/' && line.charAt(ii) != '^') {
tempB = tempB.concat(Character.toString(line.charAt(ii)));
b = Integer.parseInt(tempB);
}
}
if (containsOperator(line) == 0) {
System.out.println("= " + NumberFormat.getNumberInstance(Locale.US).format(add(a, b)));
} else if (containsOperator(line) == 1) {
System.out.println("= " + NumberFormat.getNumberInstance(Locale.US).format(subtract(a, b)));
} else if (containsOperator(line) == 2) {
System.out.println("= " + NumberFormat.getNumberInstance(Locale.US).format(multiply(a, b)));
} else if (containsOperator(line) == 3) {
System.out.println("= " + NumberFormat.getNumberInstance(Locale.US).format(divide(a, b)));
} else if (containsOperator(line) == 4) {
System.out.println("= " + NumberFormat.getNumberInstance(Locale.US).format(pow(a, b)));
}
main(null);
}
public static int add(int a, int b) {
return a + b;
}
public static int subtract(int a, int b) {
return a - b;
}
public static int multiply(int a, int b) {
return a * b;
}
public static int divide(int a, int b) {
return a / b;
}
public static int pow(int a, int b) {
return (int)Math.pow(a, b);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment