Why is my split method is not functioning as intended when I am splitting numbers from operator

Output of the code

public class Model {
private Scanner sc = new Scanner(System.in);

private String expression;
private String exp[];

    public Model()
        expression = sc.nextLine();
    public void split()
        //splitting the entered expression to array of operators alone and array of the numbers then create Arraylist to combine the operators and numbers together as if it is a string expression  but as an array
        String num[]= this.expression.split("[/+/*/-]");
        String preop[]= this.expression.split("[0123456789]"); // this will give [empty, operator, operator...] therefore we will create another array to fill in the ops excluding empty
                    System.out.println("Test: Printing num Array");
                    for(int i = 0; i<num.length;i++)
                    System.out.println("\nTest: Printing preOp Array");
                    for(int i = 0; i<preop.length;i++)
                    System.out.print(preop[i]+ ",");
        ArrayList<String> op = new ArrayList<>();//I used arraylist because easier
        for(int i = 1; i<preop.length;i++)
                System.out.println("\nTest of the fixed preOp array: " + op);
        //putting the operands and the operators together in the same array
        ArrayList<String> exp = new ArrayList<>();
        //fill the arraylist with numbers then add the operators to it by using number (index of the operator +1 +count)
        for(int i = 0; i <num.length;i++)
        int count = 0;
        for(int i = 0; i <op.size();i++)
            exp.add(i+1+count, op.get(i));
                System.out.println("Test: " + exp);

The problem is that the op array is giving empty slot [op, op, empty, op] whenever user inputs a double digit numbers in the expression.

I was expecting similar results when user enters one digit numbers where it gives the intended results as in the image input with one digit numbers

>Solution :

it is because this


You split by a single digit, so 43 is split into 2 parts as well with an empty string in between.
Also, you don’t need to name all the digits in the regex, you can just do a range "[0-9]". If you want to match for 1 or more digits add a +. This should work:


Leave a Reply