Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading