我想将数据添加到ArrayList对象.在我的代码中,addBook()方法将显示Input Dialogue Box并将此字符串传递给isbn变量.现在需要将isbn变量数据添加到ArrayList,它存在于BookInfoNew()构造函数中,但是在addBook()方法中找不到列表对象.(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);
}
}
Run Code Online (Sandbox Code Playgroud)
这是范围问题.您无法访问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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6678 次 |
| 最近记录: |