Okay... I want to get around the concept of computing negative numbers. I am self-learning and I am running to a lot of difficulty. How do implement negative input?
My code:
public class MainSystem {
public static void main(String[] args) {
try (Scanner console = new Scanner(System.in)) {
String input;
System.out.print(">>> ");
input = console.nextLine();
splitEntry(input);
System.out.println("The console is now closed.");
}
}
private static void splitEntry(String input) {
String function = "[+\\-*/]+"; //placing them in an index
String[] token = input.split(function);//and this
double num1 = Double.parseDouble(token[0]);
double num2 = Double.parseDouble(token[1]);
//double answer;
String operator = input.toCharArray()[token[0].length()] + "";
if (operator.matches(function) && (token[0] + token[1] + operator).length() == input.length()) {
System.out.println("Operation is " + operator + ", your first number is " + token[0] + " your second number is " + token[1]);
} else {
System.out.println("Your entry of " + input + " is invalid");
}
if (operator.matches(function)
&& (token[0] + token[1] + operator).length() == input.length()) {
double result = 0;
if (operator.equals("+")) { // this is simplified by using formatters
result = num1 + num2;
} else if (operator.equals("-")) {
result = num1 - num2;
} else if (operator.equals("*")) {
result = num1 * num2;
} else if (operator.equals("/")) {
result = num1 / num2;
}
System.out.printf("Your first number %.2f %s by your second number %.2f = makes for %.2f%n", num1, operator, num2,
result);
}
}
}
How do I allow my calculator to place -2 + 5 and get the answer 3?
Every time I try to do that, the program crashes? What to do to make negative numbers to be computed
No comments:
Post a Comment