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);
}
}
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);
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With