I am trying to read a line of numbers in string datatype then parse them into double before reading the next line. I get a nullpointerexception.

I am trying to read numbers 4 5 2 first, parse them to double, then do some other calculations before going to the second line of number which is 1 1 3 1.

        double num;
        String delim;
        String[] tokens = null;
        double[] numArray = null;
        String data = "4 5 2\n1 1 3 1\n";

        Scanner input = new Scanner(data);

        while(input.hasNextLine())
        {
            delim = "[ \n]+"; //separate by spaces
            tokens = data.split(delim);

            for(int i = 0; i < tokens.length; i++)
            {
                num = Double.parseDouble(tokens[i]);
                numArray[i] = num;
                System.out.print(numArray[i]); //
            }

        }

Recommended Answers

All 3 Replies

and where do you get a nullpointerexception ? can you post the stacktrace ?

Try checking what's the size of your numArray and show stacktrace as stultuske alrdy asked for

The back slash in your delim should be escaped because it is supposed to be a regex String. However, a better regex should be \\s+ instead...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.