2015-11-19 85 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'無論是。 –