Hello I have a function that reads int's separated by whitespace (0 1 0 2 0 1 0 2 0 1 0 1) and inserts position by position in a vector. This is working fine.
public void readTemplate() throws NumberFormatException, IOException {
File templateFile = new File ("C:\\Temp\\templateFile.txt");
FileReader fr = new FileReader(templateFile);
BufferedReader br = new BufferedReader(fr);
String row;
int j=0;
while((row = br.readLine()) != null) {
String[] strings = row.split(" ");
for (String str : strings) {
Integer foo = Integer.parseInt(str);
vectorTemplate[j] = foo;
j ;
}
}
br.close();
fr.close();
System.out.println("TEMPLATE FILE SUCCESFULY OPENED");
}
Now I have a new need which is to read a string on the same line.
Thinking this is the name of a bettor and their bets:
JOHN 0 1 2 1 0 1 2 2 1 0 1 0
I have a Bet type class, where I need to save the name as String and the other elements in a bet vector of this user.
I don't know how to read this first information as a string to save in my variable name and the rest of the line normally as a vector.
I have tried some alternatives but I always run into java.lang.NumberFormatException
I believe the error is in the line I left bold ( totalBets[j].setName(str); )
public void betsReads() throws IllegalArgumentException, IOException {
File betsFile = new File ("C:\\Temp\\bets.txt");
FileReader fr = new FileReader(betsFile);
BufferedReader br = new BufferedReader(fr);
for(int j = 0; j < size; j ) {
String row;
while((row= br.readLine()) != null) {
totalBets[j] = new Bet();
String[] strings = row.split(" ");
for (String str : strings) {
**totalBets[j].setName(str);**
for(int i = 0; i < bets.vectorBets.length; i ) {
Integer foo = Integer.parseInt(str);
totalBets[j].vectorBers[i] = foo;
}
j ;
}
}
}
br.close();
fr.close();
CodePudding user response:
The first String
in the array of tokens is the name. Every value after that is a bet. Also, use try-with-Resources
instead of explicitly closing. Like,
public void betsReads() throws IllegalArgumentException, IOException {
File betsFile = new File("C:\\Temp\\bets.txt");
try (FileReader fr = new FileReader(betsFile);
BufferedReader br = new BufferedReader(fr)) {
String row;
int j = 0;
while ((row = br.readLine()) != null) {
totalBets[j] = new Bet();
String[] strings = row.split("\\s ");
totalBets[j].setName(strings[0]);
for (int i = 1; i < strings.length; i ) {
int foo = Integer.parseInt(strings[i]);
totalBets[j].vectorBers[i - 1] = foo;
}
}
}
}