我想将数据添加到ArrayList对象。在我的代码中,addBook()方法将显示“输入对话框”,并将此字符串传递给isbn变量。现在需要将isbn变量数据添加到驻留在BookInfoNew()构造函数中但在addBook()方法中找不到的列表对象的ArrayList中。 (list.add(isbn))
请帮助我。
import java.util.*;
import javax.swing.JOptionPane;
public class BookInfoNew {
private static String isbn;
private static String bookName;
private static String authorName;
public static int totalBooks = 0;
//default constructor
public BookInfoNew() {
List<String> list = new ArrayList<String>(); //create ArrayList
}
//Parameterized constructor
public void BookInfoNew(String x, String y, String z) {
isbn = x;
bookName = y;
authorName = z;
}
//add book method
public void addBook() {
String isbn = JOptionPane.showInputDialog("Enter ISBN");
//add books data to ArrayList
list.add(isbn);
}
}
最佳答案
这是范围的问题。您无法访问list
对象中的addBook()
对象。因此,您必须将list
设置为addBook()
的参数,或者将其设置为全局变量。
此代码使用全局变量对其进行了修复:
import java.util.*;
import javax.swing.JOptionPane;
public class BookInfoNew {
private String isbn;
private String bookName;
private String authorName;
public int totalBooks = 0;
// global list variable here which you can use in your methods
private List<String> list;
//default constructor
public BookInfoNew() {
list = new ArrayList<String>(); //create ArrayList
}
//Parameterized constructor - constructor has no return type
public BookInfoNew(String x, String y, String z) {
isbn = x;
bookName = y;
authorName = z;
}
//add book method
public void addBook() {
String isbn = JOptionPane.showInputDialog("Enter ISBN");
//add books data to ArrayList
list.add(isbn);
}
}