简体   繁体   English

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

[英]list.add() does not add data to ArrayList

I want to add data to ArrayList object. 我想将数据添加到ArrayList对象。 In my code addBook() method will be show Input Dialogue Box and pass this string to isbn variable. 在我的代码中,addBook()方法将显示Input Dialogue Box并将此字符串传递给isbn变量。 Now there is need to add isbn variable data to ArrayList which is reside in BookInfoNew() constructor but list object not found in addBook() method. 现在需要将isbn变量数据添加到ArrayList,它存在于BookInfoNew()构造函数中,但是在addBook()方法中找不到列表对象。 (list.add(isbn)) (list.add(ISBN))

kindly help me. 请帮助我。

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

This is an issue with scope. 这是范围问题。 You cannot access your list object within the addBook() object. 您无法在addBook()对象中访问list对象。 So, you have to either make list a parameter to addBook() or you can make it a global variable. 因此,您必须使list成为addBook()的参数,或者您可以使其成为全局变量。

This code fixes it using a global variable: 此代码使用全局变量修复它:

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

You should rewrite your code a little bit like that: 您应该像这样重写您的代码:

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

and it should be ok. 它应该没问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM