NoCanDo NoCanDo - 1 month ago 5x
Java Question

Arrays with different datatypes i.e. strings and integers. (Objectorientend)

For example I've

3 books:

Booknumber (int), Booktitle (string), Booklanguage (string), Bookprice (int).

now I want to have an array called

I'm gettin the data I set via setBooknumber like this:

Book1.getBooknumber(), Book1.getBooktitle(),...,Book3.getBookprice().

Now how do I realize this
books[3][4] array
. I can't call it
String books[][] = new String [3][4]
. Because I can't get
Booknumber (int)
into it.

I don't want Booknumber to be String neither Bookprice. How do I realize it, please?

Now to further elaborate it.

I have 2 classes.

public class book{
String Booktitle, Booklanguage;
int Booknumber, Bookprice;





public class bookUI
public static void main(String arg[])
book book1 = new book();
book book2 = new book();
book book3 = new book();


//Here I want to have books[3][4] Array. And gettin the data via book1.get...book3.get into the array

public class Book
    public int number;
    public String title;
    public String language;
    public int price;

    // Add constructor, get, set, as needed.

then declare your array as:

Book[] books = new Book[3];

EDIT: In response to O.P.'s confusion, Book should be an object, not an array. Each book should be created on it's own (via a properly designed constructor) and then added to the array. In fact, I wouldn't use an array, but an ArrayList. In other words, you are trying to force data into containers that aren't suitable for the task at hand.

I would venture that 50% of programming is choosing the right data structure for your data. Algorithms naturally follow if there is a good choice of structure.

When properly done, you get your UI class to look like: Edit: Generics added to the following code snippet.

ArrayList<Book> myLibrary = new ArrayList<Book>();
myLibrary.add(new Book(1, "Thinking In Java", "English", 4999));
myLibrary.add(new Book(2, "Hacking for Fun and Profit", "English", 1099);


now you can use the Collections interface and do something like:

int total = 0;
for (Book b : myLibrary)
   total += b.price;
   System.out.println(b); // Assuming a valid toString in the Book class
System.out.println("The total value of your library is " + total);