Question: Java - Allow spaces in given equation & Print error when divisible by zero I have my code: import java.util.Scanner; public class Calculator { public

Java - Allow spaces in given equation & Print error when divisible by zero

I have my code:

import java.util.Scanner; public class Calculator { public static void main(String [] args) { Scanner input = new Scanner(System.in); System.out.println("Enter String: "); String userInput = input.next(); System.out.println("The answer is " + calculate(userInput)); } public static double calculate(String inp){ String operators [] = inp.split("[0-9]+"); String operands [] = inp.split("[+-/*]"); double identify = Double.parseDouble(operands[0]); for(int i=0;i < operands.length;i++){ if(operators[i].equals("+")) identify += Double.parseDouble(operands[i]); else if(operators[i].equals("-")) identify -= Double.parseDouble(operands[i]); else if(operators[i].equals("*")) identify *= Double.parseDouble(operands[i]); else if (operators[i].equals("/")) identify /= Double.parseDouble(operands[i]); } double result = identify; return result; } }

I would like to make it accept my string with any given number of spaces in the given equation, also when divide by zero error happens, print an Error message from the method calculate. -

Examples-

Enter String: 6 - 3.0

The answer is 3.0

Enter String:

12 / 0

Error!

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!