list.add()不会向ArrayList添加数据

时间:2015-11-19 08:02:33

标签: java arraylist

我想将数据添加到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);
    }
}

2 个答案:

答案 0 :(得分:8)

这是范围问题。您无法访问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);
    }
}

答案 1 :(得分:1)

您应该稍微重写一下代码:

{{1}}

它应该没问题。