I am working on a calculator in java. I have a method that parses the user input as a String to a double array. I take in a string, and convert it to a double array with a split method that takes a '+' as a delimiter. This code only works for addition operations. Here is that code:
public static double[] parseInput(String input){
// creates a String array that contains the elements of the input without the plus signs
String [] pieces = input.trim().split("\\+");
// creates a double array the same size as the string array previous to this
double[] nums = new double [pieces.length];
// loops through each index of the string array, parses and places the element into the double array
for(int i = 0; i < nums.length; i++){
nums[i] = Integer.parseInt(pieces[i]);
}
// returns the double array
return nums;
}
I need to make this work for other operations as well, such as subtraction, multiplication, etc... I also need to make it work for when the user does multiple operations in the same line, such as 1+3-2.
I am not worried about the math part of this, only the parsing. Bottom line is this. I need to make an array that contains the numbers being operated on, as well as the operations.
Bonus points if we can get it to work with spaces between numbers. This code currently works for "1+1" but breaks for "1 + 1".
Thank you in advance.