I primarily code in Python and I am completely new to java, so I am having difficulty with a simple programming task in Java regarding parsing through a .csv file. My .csv file has multiple columns and I want to parse through each line and store the second column as a string and the last column (column 4) as a double as a (string, double) pair. However, if column four does not contain a value that can be cast as a double value, I would like to assign a 0.0 as the double in the pair for that line. Each line from the .csv is passed to this function below, and I attempt to store the (string, double) pairs as mentioned, but after executing, all the pairs have 0.0 as the double value. I am not sure if there is there is a problem in my try/catch or looping method through each token. Any hints are appreciated.
public void a(Text t) {
StringTokenizer word = new StringTokenizer(t.toString(), ", ");
int count = 0;
double val = 0.0;
String keep = new String("");
boolean loop = true;
while (loop) {
String nextWord = word.nextToken ();
if (count == 2) {
//string in pair
keep = nextWord;
//loop until at last column and store word
while (word.hasMoreTokens()){
nextWord = word.nextToken();
}
loop = false;
//check if string can be cast to double
try{
Double.parseDouble(nextWord);
} catch(NumberFormatException e) {
val = 0.0;
} catch(NullPointerException e) {
val = 0.0;
}
val = Double.parseDouble(nextWord);
}
count++;
}
// then not relevant code to store (keep, val) pair for rest of code
}
string.split(",")it will be better and faster.StringTokenizeris a depricated library. It will give you an array of string and performing operations on it will be easy as well.val = Double.parseDouble(nextWord);Did you mean to do that parsing and assignment inside thetryblock?StringTokenizer: StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.