Skip to content
Advertisement

How to convert a string that contains doubles into a matrix in java

JavaScript

Here we have a String of 9 numbers, some of which are double, and some of which are int. I need to convert this into a matrix and when I am given only integer values in the String, it is fairly easy because all I do cast double on a whole integer after I parseInt for each String value that is a digit.

For instance,

JavaScript

This gives me a 3-by-3 matrix that goes from 1-9. However, when I am given a string that contains real numbers or ‘doubles’ my method fails to create a matrix because it counts each element of the string, one of which is a period. So how can I create a 3-by-3 matrix when the String that is given to me contains a double?

Advertisement

Answer

Answer by @rempas is good, though I would replace the calculation of the input index with a simple “next value” index.

JavaScript

Output

JavaScript

Jagged Array

That will make it work even if the 2D array is jagged.

JavaScript

Output

JavaScript

Scanner

Alternatively, instead of split() and k++ logic, use a Scanner.

JavaScript

Output

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement