Wave
Wave

Reputation: 45

How to print Array from Class A in Class B in java?

This is my first question here so sorry if I'm not doing it right.

I don't know how to show my array in another class, what should I do?

Here's my main code

public class Library {
  public static void app() {
        int choise;
        do {
            System.out.print("Choose option \n 1.Fill_Array \n 2. Show_Array \n 0. End \n> ");
            choise = read_N.nextInt();

            switch (choise) {
                case 1:
                    Fill.fill_base();
                    break;
                case 2:
                    Show.show_base();
                    break;
                case 0:
                    break;
            }
        } while (choise != 0);
    }

    public static void main(String[] args) {
        System.out.println("Welcome in Library_Database");
        app();
    }
}

My filing class

Here user giving Strings to array, filing this 2 arrays

  public class Fill {
    public static void fill_base() {
        System.out.println("Fill array with books title");

        for (int i = 0; i < tab_b.length; ++i) {
            System.out.print("Title nr. " + (i + 1) + " > ");
            tab_b[i] = read_S.nextLine();
            System.out.print("Category: ");
            tab_c[i] = read_S.nextLine();
        }

        System.out.println();
    }
}

My discharging class

Right now I dont know what to do.. ;/ Create object Fill fill = new Fill(); or sth else :/ I wanna use dziś class and function to show array elements in Library class.

public class Show {
    public static void show_base() {
        for (int i = 0; i < Fill.tab_b.length; ++i) {
            System.out.print("Title nr. " + (i + 1) + " > ");
            System.out.println(Fill.tab_b[i]);
            System.out.print("Category: ");
            System.out.println(Fill.tab_c[i]);
        }
        System.out.println();
    }
}

Upvotes: 0

Views: 65

Answers (1)

Stefan Freitag
Stefan Freitag

Reputation: 3608

If I understood you right, you have one class used for filling the information in and a second for showing the information. (To be honest, I do not really understand why you split up the code into to classes.)

To give you an idea on dealing with your problem: think of using the return-value of the fill_base() method. Instead of returning void you could return the list of filled arrays. By doing so, you could e.g. get rid of the public modifiers of the arrays in the class Fill.

In the switch-statement in your method app() you could store the returned value from fill_base(). If 2 is entered, you could pass the stored list of arrays to the method show_base().

Upvotes: 1

Related Questions