Reputation: 5
any help will be appreciated.
print some details about fines on it, but the code is not giving me an output.
my code is :
Upvotes: 0
Views: 49
Reputation: 69
class BookLib{
String userName ;
String bookName;
int noOfDays;
int fine;
@Override
public String toString() {
return "BookLib{" +
"userName='" + userName + '\'' +
", bookName='" + bookName + '\'' +
", noOfDays=" + noOfDays + '}';
}
}
class Library{
List<BookLib> books = new ArrayList<>();
void readDetails() throws IOException{
FileReader fr = new FileReader("fineDetails.txt");
BufferedReader br = new BufferedReader(fr);
String thisLine;
List<String> lines = new ArrayList<>();
while ((thisLine = br.readLine()) != null) {
lines.add(thisLine);
}
for(String readLine: lines){
StringTokenizer stringTokenizer = new StringTokenizer(readLine, ",");
BookLib tempBook = new BookLib();
tempBook.userName = stringTokenizer.nextToken().trim();
tempBook.bookName = stringTokenizer.nextToken().trim();
tempBook.noOfDays = Integer.parseInt(stringTokenizer.nextToken().trim());
System.out.println("BookLib = " + tempBook);
books.add(tempBook)
}
br.close();
fr.close();
}
I Hope, Above code, is helping you for handling NumberFormatException and future ArrayIndexOutOfBoundException handling. you may also use try-catch {} for handling these errors.
Upvotes: 1
Reputation: 2575
The problem is that you can't parse the String "25 " to an Integer because of the whitespace. You can remove the whitespace using the trim method of String like this:
//...
book[i].userName = stringTokenizer.nextToken();
book[i].bookName = stringTokenizer.nextToken();
book[i].noOfDays = Integer.parseInt(stringTokenizer.nextToken().trim()); // trim here
//...
I think there is another problem that didn't cause any errors yet, because the NumberFormatException
occured earlier: You do close the readers br
and fr
in the for loop, but they will still be used there. You should move the lines br.close()
and fr.close()
down to the end of the method.
Upvotes: 1