Home > Enterprise >  Is there a way to get rid of this 0 in an array?
Is there a way to get rid of this 0 in an array?

Time:10-25

I've got a problem with app I'm creating

                String[] wspolczynnikiText = wzorFunkcjiText.split("[ x\\s]", 0);
            int[] wspolczynniki = new int[wspolczynnikiText.length];
            for (int i = 0; i < wspolczynnikiText.length; i  ) {
                try{
                    wspolczynniki[i] = Integer.parseInt(wspolczynnikiText[i]);
                }
                catch (NumberFormatException nfe){
                }
            }

So basically it takes user input (sorry for variable names in my native language) and splits it, works good, for example in input "5 4x" it only reads 5, 4 values as it should, but when input is for example "5x 5" it reads 5, 5, 0 values. Is there a way for it to don't happen? Thanks in advance!

CodePudding user response:

You are splitting on or x (or space). So "5x 5" will be split into ["5", "", "5"].

Arrays are zero-initialized. Since the second element cannot be parsed as an int, you end up with [5,0,5].

For input "5 4x", after splitting you have ["5", "4"], which will give you [5,4] after parsing.

The second argument to split will remove trailing empty strings, see String#split:

If the limit is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

Note that calling str.split("regex", 0) is identical to the shorter str.split("regex").

It's probably easier to use an ArrayList to append elements and then convert it to an array after the loop (if you really need an array; lists provide more functionality and are easier to use). Using a list also does work for you of keeping track of the current index.

  • Related