I'm learning java. I have trouble when I click JButton to load data from text file to JList, but it notices error "java.lang.NumberFormatException: For input string: """. First of all, I input data from 4 JTextField to JList then save file text. My txt file has content: 1-java-3-4. Someone help me, please. Thank. Here is my code button save and load data:
private void btAddBookActionPerformed(java.awt.event.ActionEvent evt) {
String BookId = txtBookID.getText();
String BookName = txtBookName.getText();
String Quantity = txtQuantity.getText();
String Price = txtPrice.getText();
if(BookId.equals("")|| BookId.equalsIgnoreCase("Type Here") || BookName.equals("")|| BookName.equalsIgnoreCase("Type Here") || Quantity.equals("")|| Quantity.equalsIgnoreCase("Type Here")||Price.equals("")|| Price.equalsIgnoreCase("Type Here")){
txtBookID.setText("Type Here");
txtBookName.setText("Type Here");
txtPrice.setText("Type Here");
txtQuantity.setText("Type Here");
}else{
listmodel.addElement(BookId+"-"+BookName+"-"+Quantity+"-
"+Price);
booklist.setModel(listmodel);
txtBookID.setText("");
txtBookName.setText("");
txtQuantity.setText("");
txtPrice.setText("");
}
private void btLoadDBActionPerformed(java.awt.event.ActionEvent evt) {
BufferedReader br = null;
try{
br = new BufferedReader(new FileReader("BookList.txt"));
int val = Integer.parseInt(br.readLine());
for (int i = 0; i < val; i++) {
String ss = br.readLine();
listmodel.addElement(ss);
}
booklist.setModel(listmodel);
}
catch(Exception e){
System.out.println(""+e);
}
finally{
try{
br.close();
}
catch(Exception e){
System.out.println(""+e);
}
}
}
Looking closer at your code, it seems that you don't need the integer-parsing at all. The problem is that you're reading the file the wrong way. Instead of a for
loop, a common idiom for reading a text file line-by-line (when you don't know the exact size of the file) is with a while
loop as follows:
br = new BufferedReader(new FileReader("BookList.txt"));
String line;
while ((line = br.readLine()) != null) {
listmodel.addElement(line);
}
booklist.setModel(listmodel);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.