-1

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.

  • [`String::split`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/String.html#split(java.lang.String)) takes a regex. We can construct a regex that splits the `String` to our liking. – Turing85 Oct 31 '21 at 19:12
  • You might also be interested in https://en.wikipedia.org/wiki/Shunting-yard_algorithm – Kayaman Oct 31 '21 at 19:13

2 Answers2

0
String str = "word1, word2 word3@word4?word5.word6";
String[] arrOfStr = str.split("[, ?.@]+");
 
for (String a : arrOfStr)
    System.out.println(a);

would give:

word1
word2
word3
word4
word5
word6

This should give your desired result

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
0
input: 
 double[] spacesNum = parseInput("4- 8 +3- 12* 34/ 45");

parser: 
String [] pieces = input.trim().replaceAll("\\s+", "").split("[-+*/]");

somayaj
  • 56
  • 3
  • 1
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. You can find more information on how to write good answers in the help center: https://stackoverflow.com/help/how-to-answer . Good luck – nima Oct 31 '21 at 20:27