Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

list.add() does not add data to ArrayList

Tags:

java

arraylist

I want to add data to ArrayList object. In my code addBook() method will be show Input Dialogue Box and pass this string to isbn variable. 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. (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);
    }
}
like image 699
Zohaib Siddique Avatar asked Jan 08 '23 03:01

Zohaib Siddique


2 Answers

This is an issue with scope. You cannot access your list object within the addBook() object. So, you have to either make list a parameter to addBook() or you can make it a global variable.

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);
    }
}
like image 113
jiaweizhang Avatar answered Jan 19 '23 10:01

jiaweizhang


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.

like image 25
user3056857 Avatar answered Jan 19 '23 11:01

user3056857