I want to “parse” a given string into vectors. A vector starts with “[” and ends with “]”. The values of the vector as well as the vectors themself are seperated by “,”. If I use integers as values my code works fine “[1,2,3],[5,2,3],[1,6,3]”. But when I mix integer values with double values “[1,2.5,3],[5,2,3],[1,6,3]” stringtokenizer returns wrong values (in this case “1” “2.5” but then “3]” ……)
String s = "[1,2.5,3],[5,2,3],[1,6,3]";
Vector<Vector<Double>> matrix = new Vector<Vector<Double>>();
for(int j=0;j<s.length();j++) {
if (s.charAt(j)=='[') {
int k=s.indexOf("]");
StringTokenizer st = new StringTokenizer(s.substring(j+1, j+k));// j+k-1 does not work either
Vector<Double> vector = new Vector<Double>();
while (st.hasMoreTokens()) {
vector.add(Double.parseDouble(st.nextToken(",")));//Exception in thread "main" java.lang.NumberFormatException: For input string: "3]"
}
matrix.add(vector);
}
}
Finds the index of the first occurrence of
]ins, starting from the beginning of the string. What you really want is to find the first occurrence after the start of current vector:The reason it works when you just have
2instead of2.5is that the number of characters in each vector just happened to be the same, so taking the fist occurrence of]to calculate the length of the vector worked by luck.Note, you will also have to change the end index of your
substringcall tok:As a side note, use of
StringTokenizeris not recommended. In this case you should be usingsplit()instead: