2015-11-19 73 views
3

我想将数据添加到ArrayList对象。在我的代码中,addBook()方法将显示Input Dialogue Box并将此字符串传递给isbn变量。现在需要将isbn变量数据添加到驻留在BookInfoNew()构造函数中但不在addBook()方法中找到的列表对象的ArrayList中。 (list.add(isbn))list.add()不会将数据添加到ArrayList

请帮助我。

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); 
    } 
} 
+3

因为'list'是一个局部变量,它只存在于你的非参数构造函数中。 – SomeJavaGuy

+1

为什么其他字段是静态的? – Manu

+0

你的问题标题是错误的,因为你的'addBook()'甚至不能访问'list' – Ramanlfc

回答

8

这是范围问题。您无法访问addBook()对象内的list对象。因此,您必须将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); 
    } 
} 
+0

请好心编辑我的代码 –

+0

你的代码已被编辑。正如@manu问,为什么你的其他变量是静态的? – jiaweizhang

+0

现在list.add(isbn)不起作用。它说list.add(isbn)方法是未定义的。 –

1

你应该重写代码有点像:

... 
List<String> list = null; 
public BookInfoNew() { 
    list = new ArrayList<String>(); //create ArrayList 
} 
... 

,它应该没问题。

+1

无需'= NULL;' – jiaweizhang

+0

并没有什么错的,如果设置为'null'无论是。 –