Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have two of the following java classes (listed below) Class BookInfo declares static block of arrays

     public class BookInfo {

    // Global arrays accessible by all methods

    public static String[] isbnInfo;
    public static String[] bookTitleInfo;
    public static String[] authorInfo;
    public static String[] publisherInfo;
    public static String[] dateAddedInfo;;
    public static int[] qtyOnHandInfo;
    public static double[] wholesaleInfo;
    public static double[] retailInfo;

    static {

        isbnInfo = new String[] {

                                "978-0060014018",
                                "978-0449221431",
                                "978-0545132060",
                                "978-0312474881",
                                "978-0547745527"

                                };

        bookTitleInfo = new String[] {

                                "The Greatest Stories",
                                "The Novel",
                                "Smile",
                                "The Bedford Introduction to Drama",
                                "AWOL on the Appalachian Trail"

                                };

        authorInfo = new String[]  {

                                 "Rick Beyer",
                                 "James A. Michener",
                                 "Raina Telgemeier",
                                 "Lee A. Jacobus",
                                 "David Miller"

                                };

        publisherInfo = new String[] {

                                "HerperResource",
                                "Fawcett",
                                "Graphix",
                                "Bedford St. Martins",
                                "Mariner Books"

                                };

        dateAddedInfo = new String[] {

            "05/18/2003", 
            "07/07/1992", 
            "02/01/2010", 
            "09/05/2008", 
            "11/01/2011"

            };

        qtyOnHandInfo = new int[] {7, 5, 10, 2, 8};

        wholesaleInfo = new double[] {12.91, 7.99, 6.09, 54.99, 10.17};

        retailInfo = new double[] {18.99, 3.84, 4.90, 88.30, 14.95};

    }

    public static void BookInfo() {

        System.out.println("             Serendipity Booksellers");
        System.out.println("                Book Information\n");       


        for(int i = 0; i < isbnInfo.length; i++){

            System.out.println("ISBN: " + isbnInfo[i]);
            System.out.println("Title: " + bookTitleInfo[i]);
            System.out.println("Author: " + authorInfo[i]);
            System.out.println("Publisher: " + publisherInfo[i]);
            System.out.println("Date Added: " + dateAddedInfo[i]);
            System.out.println("Quantity-On-Hand: " + qtyOnHandInfo[i]);
            System.out.println("Wholesale Cost: $ " + wholesaleInfo[i]);
            System.out.println("Retail Price: $ " + retailInfo[i]);
            System.out.println();

        }
    }
    }

How do I access array list from this class? Only the following is working so far but how do I modify (add, delete, edit, etc) from this class (there is no main main in this class) BookInfo bookinfo = new BookInfo(); bookinfo.BookInfo(); System.out.println(bookinfo.isbnInfo[0]); how do I modify (add, delete, edit, etc) from the main menu

    import java.util.Scanner;

     public class InvMenu {
     public static void addBook(){

      System.out.println("\nYou selected Add a Book\n");
       BookInfo bookinfo = new BookInfo();
      bookinfo.BookInfo(); // only these two are working but I cannot modify arrays at all
      System.out.println(bookinfo.isbnInfo[0]);

        }

       public static void editBook(){

     System.out.println("\nYou selected Edit a Book's Record\n"); 

     }

     public static void deleteBook(){

      System.out.println("\nYou selected Delete a Book\n");

    }

    public static void printInvMenu(){

    String choice;
    int x = 0;
    boolean b;
    char letter;
    boolean menu = true;

    Scanner keyboard = new Scanner(System.in);

    System.out.println("Serendipity Booksellers");
    System.out.println("Inventory Database\n");
    System.out.println("       1. Look Up a Book");
    System.out.println("       2. Add a Book");
    System.out.println("       3. Edit a Book's Record");
    System.out.println("       4. Delete a Book");
    System.out.println("       5. Return to the Main Menu\n");

    do{

    System.out.print("Enter your choice: ");
    choice = keyboard.nextLine();
    b = true;

    try {
        x = Integer.parseInt(choice);
        System.out.println(x);

    }

    catch(NumberFormatException nFE) {

        b = false;
        System.out.println("You did not enter a valid choice. Try again!\n");

    }

       }while(b == false);

    do{

    else if(x == 1){

        addBook();

    }

    else if(x == 2){

        editBook();

    }

    else if(x == 3){

        deleteBook();

    }

    else if(x == 4){

        System.out.println("Returning to the Main Menu\n");
        break;

    }

    else{

        System.out.println("\nYou did not enter a valid choice. Try again!\n");

    }

     printInvMenu();

    }while(x == 5);

      }
     }

I can easily access some of the functionality from the other class main menu: BookInfo bookinfo = new BookInfo(); bookinfo.BookInfo(); System.out.println(bookinfo.isbnInfo[0]); How do I modify (add, delete, edit, etc) from the main menu? Any ideas, suggestions are greatly appreciated!

share|improve this question

closed as not a real question by bmargulies, Ram kiran, Piotr Gwiazda, S.L. Barth, kapa Oct 19 '12 at 9:08

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.If this question can be reworded to fit the rules in the help center, please edit the question.

1  
You say "How do I access array list from this class?" but you don't define what you mean by "array list". –  Hot Licks Oct 19 '12 at 1:06

5 Answers 5

up vote 2 down vote accepted

You simply can not "add" a new element to an Array after you have created it. From oracle tutorials page:

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.

Thus, if you want to add and remove elements from a List I recommend you to use an ArrayList object, which can be defined as a

Resizable-array implementation of the List interface.

You could for example replace your line of code

private static String[] isbnInfo;

for

private static ArrayList<String> isbnInfo;

and initialize it like:

isbnInfo = new ArrayList<String>()
isbnInfo.add("978-0060014018");
isbnInfo.add("978-0449221431");
isbnInfo.add("978-0545132060");
isbnInfo.add("978-0547745527");

As for edit your array, you can simply add some public getters for your private fields

public static String[] getIsbnInfo()
{
   return isbnInfo;
}

and in your public class:

String[] isbnInfo = BookInfo.getIsbnInfo();

You can also use a public method to edit your arrays, like:

public static void replaceIsbnInfo(int index, String isbn)
{
   isbnInfo[index] = isbn;
}

And in your menu class

BookInfo.replaceIsbnInfo(1, "978-0547745527");

I hope it helped. Cheers!

share|improve this answer
    
You can, however, create a new array, then use System.arraycopy to copy the entries from the old array to the new one, then swap the new array in in place of the old one. –  Hot Licks Oct 19 '12 at 1:07
    
Yes, but isn't it easier and prettier to use an ArrayList? –  Bruno Vieira Oct 19 '12 at 1:16
    
Sometimes, sometimes not. If modifications are rare, the straight array is more efficient and less cumbersome. If modifications are frequent the ArrayList (or some other aggregation object) is better. And it's good to know how to use the straight array scheme, just as a conceptual thing. –  Hot Licks Oct 19 '12 at 1:20
    
ArrayList stil easier and prettier. Although I must agree that an example using only arrays would elucidate better the concept of the array scheme. –  Bruno Vieira Oct 19 '12 at 2:23
    
Pretty is in the eye of the beholder -- I like my arrays naked, not all dressed up. –  Hot Licks Oct 19 '12 at 2:29

You've kind of mucked this thing up.

You should first create a "BookInfo" class (but not the one you defined) that contains instance fields of isbnInfo, bookTitleInfo, authorInfo, etc. (Just one entity for one book per field, not an array.)

Then, for each book, create and initialize the corresponding BookInfo object.

Next, either place the collection of such BookInfo objects in a searchable object such as a HashMap (for a single search field), or place them in an array of some sort and build separate HashMaps or whatever to map from search arguments to array index (anchoring all the pieces in a "Library" object).

When someone searches for a book, return the BookInfo object, which can have "getter" methods to extract the (ideally private) instance field values. This returns all info about the book in one piece.

share|improve this answer

You've declared the arrays as private, so they are private. You would have to write +accessor methods+ to return the respective arrays, or more elegantly write methods that access, search, modify, etc individual array entries.

share|improve this answer
    
Would it be reasonable to change them to public? –  Vladimir Oct 19 '12 at 0:55
    
@Vladimir All the Object-Oriented Programming experience of the last 25 years says 'no'. Write methods. –  EJP Oct 19 '12 at 2:56

If i understand correctly, you want to access values of an array, or any variable/function for that matter from a different class file?

ClassName.VariableName = whatever;

when you use

ClassName variable = new ClassName();

it runs that class every time you call it.make sure your variable is

public static VariableType Variablename;

or you wont be able to call/change it

share|improve this answer

ArrayList seem to be the most flexible out of all the options. Even Effective Java 2nd Edition, Item 25: Prefer lists to arrays. Thanks for all your input!

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.