Storing object into an array - Java - java

I am relatively new to Java and I have taken some light courses on it. I am trying to emulate an exercise that I had a while back and I am having some trouble.
I have two classes. One is taking in data and the other is storing it.
public class Car{
public Car(String name, String color)
{
this.name = name,
this.color = color
}
How can I store this into the array (not an array list) that I created in this class:
public class CarDatabase {
Car[] carList = new Car[100];
public CarDatabase()
{
// System.out.println("test");
}
public void createAccount(String name, String color)
{
// this is where I am having trouble
for (int i = 0; i < carList.length; i++)
{
System.out.println("Successfully created: " + name +
"." + "Color of car: " + color);
break;
}
}
I don't have a main method yet but I will need one later on to for example, PRINT out this array and that is what I can't wrap my head around - how do I store DATA/OBJECTS into the "CarDatabase" array so I can call methods with it later (instead of just being able to print it)?
Any help would be appreciated.
Thanks!

Not really sure what you are trying to achieve but I'll give it a go.
You could modify your CarDatabase class like so -
public class CarDatabase {
Car[] carList = new Car[100];
int carsStored;
// No need for a constructor since we don't need any initialization.
// The default constructor will do it's job.
public void createAccount(String name, String color) {
carList[carsStored++] = new Car(name, color);
}
}
And your main method could look like -
public static void main(String[] args) {
CarDatabase database = new CarDatabase();
database.createAccount("Lambo", "Red");
database.createAccount("Punto", "White");
// To loop through your database, you can then do
for(int i = 0; i < database.carList.length; i++) {
Car car = database.carList[i];
// Now you can call methods on car object.
}
}
Hope that helps.

Related

Store different object type in one array and print each one with their methods

I am trying to create a parent class for cars and subclasses from it. Each one has separate methods and store them in an array then if the class are subclass try to call the method on it.
Parent class
public class car {
public String name ;
public double price ;
public car (String name , int price) {
this.name = name ;
this.price = price;
}
public String toString() {
return "car name : "+this.name
+" Price : " +this.price ;
}
}
Sub class
public class CarMotors extends car {
public float MotorsCapacity ;
public CarMotors( String name, int price , float MotorsCapacity) {
super(name, price);
this.MotorsCapacity = MotorsCapacity ;
}
public float getMotorsCapacity() {
return this.MotorsCapacity;
}
}
Main class
public class Test {
public static void main(String[] args) {
car [] cars = new car[2] ;
cars[0] = new car("M3" , 78000);
cars[1] = new CarMotors("M4" , 98000 , 3.0f);
for(int i=0 ;i<2;i++){
if(cars[i] instanceof CarMotors) {
System.out.println(cars[i].getMotorsCapacity()); // error here
}else {
System.out.println(cars[i].toString());
}
}
}
}
As you can see, I can't print the getMotorsCapacity(). I am new to Java. I think there is a cast that need to happen, but I don't now how.
Being short... a class only can see what its yours behaviors.
In your example CarMotors is a Car, that's fine.
But the behavior getMotorsCapacity() is created in CarMotors and it wasn't in Car.
That error occurs because, it's OK in a variable Car you are able to put an instance of CarMotors because CarMotors is a Car. So, any method that is in Car is also in CarMotors, yes, you can call. Look at cars[i].toString() there's no problem here.
You need explicitly say to compiler:
"- oh, right, originally this variable is a Car, but I know that is a CarMotors inside that. I will make a cast here, OK compiler? Thanks."
System.out.println(((CarMotors) cars[i]).getMotorsCapacity());
Or, to be more clear:
CarMotors carMotors = ((CarMotors) cars[i]);
System.out.println(carMotors.getMotorsCapacity());

Trying to create a class that contains objects from another class

I have created a class called Album, which is this one:
public class Album {
private String Titulo;
private int temas;
private int ano;
public Album(String Titulo2, int temas2, int ano2) {
this.Titulo = Titulo2;
this.temas = temas2;
this.ano = ano2;
}
public Album(String Titulo2, int temas2) {
this.Titulo = Titulo2;
this.temas = temas2;
}
public int getAno() {
return this.ano;
}
public int getTemas() {
return this.temas;
}
public String getTitulo() {
return this.Titulo;
}
public void setAno(int ano) {
this.ano = ano;
}
public boolean foiEditadoNesteSeculo() {
if (this.ano > 2000) {
return true;
} else {
return false;
}
}
public void adicionaTemasBonus(int x) {
this.temas += x;
}
public void mostraAlbum() {
System.out.println(this.Titulo + " (editado em " + this.ano + "; tem " + this.temas + " temas)");
}
}
It works fine. The problem is that the teacher asked me to create a new class called Band and it has to have an array of Albums. The Band object should be declared with an int that represents the limit of the number of albums (the length of the array). I already have some idea on how to work with arrays, but I have no idea on how to create a type of array that contains objects from another class, and after how to use the attributes of the objects to return something. I think I can figure out the rest after I'm able to properly create the class, though.
Apologies, as it has been described in Portuguese and I don't have much experience in translating.
In my opinion this would be easier to manage with a List so you can add as many Albums as you want at any time, however, since the problem statement required Array I made an example of a Band class.
I also included main method to test the program at the bottom of the Band class:
public class Band {
private int totalAlbums;
private Album[] albums;
private int currentNumberOfAlbums;
public Band(int totalAlbums) {
this.totalAlbums = totalAlbums;
this.albums = new Album[totalAlbums];
this.currentNumberOfAlbums = 0;
}
public Band(Album[] albums) {
this.totalAlbums = albums.length;
this.albums = albums;
this.currentNumberOfAlbums = this.totalAlbums;
}
public void addNewAlbum(String titulo, int temas, int ano) {
if (this.currentNumberOfAlbums == totalAlbums) {
System.out.println("Warning: Cannot add any more albums, limit reached.");
return;
}
this.albums[this.currentNumberOfAlbums++] = new Album(titulo, temas, ano);
}
public void printAlbums() {
for (Album a : this.albums) {
a.mostraAlbum();
}
}
public static void main(String [] args) {
Band b = new Band(3);
b.addNewAlbum("The First", 4, 2001);
b.addNewAlbum("The Second", 98, 2055);
b.addNewAlbum("The Finale", 12, 2011);
b.addNewAlbum("The Extra", 12, 2111);
b.printAlbums();
}
}
There are a few things to look for in this code.
First, to address your direct question, you can simply use a custom class as an array like any other class/primitive with Album[].
Secondly, you will require a Band constructor that instantiates the array of Album based on an integer passed to it, so you know how many albums are the limit. You can see this with the this.albums = new Album[totalAlbums]; line.
Next, you need a way to add a new Album into the array of Album[]. This can be done a few different ways, but the way I chose was to create a method addNewAlbum(String, int, int) to do it for this example which will also increase currentNumberOfAlbums by 1 every time a new album is added. This is useful so you know when an Album is attempted to be added even though the totalAlbums are already full! This will prevent an ArrayIndexOutOfBoundsException in your code if addNewAlbum is called too many time.
Lastly, in addNewAlbum you need to call your Album constructor with new Album(titulo, temas, ano).
In my example main, a Band with limit of 3 albums is created, and 4 albums are attempted to be added into it, with the first 3 adding successfully, and the 4th not being added, but instead printing a warning for being outside the limit.
I also added a printAlbums() method which will use your mostraAlbum() to print each Album in the albums array.
Output:
Warning: Cannot add any more albums, limit reached.
The First (editado em 2001; tem 4 temas)
The Second (editado em 2055; tem 98 temas)
The Finale (editado em 2011; tem 12 temas)
EDIT:
I added the Band(Album[] albums) constructor, you can call this with:
Album[] albums = new Album[3];
//Add your albums into this variable
Band b = new Band(albums);
public class Band {
private Album[] albums;
private numberOfAlbums;
//...
// create an empty constructor
Band(){
albums = new Album[];
numberOfAlbums = 0;
}
// constructor that receives the albums
Band(Album[] albums){
this.albums = albums;
this.numberOfAlbums = albums.length;
}
// constructor that receives the number of albums
Band(int numOfAlbums){
this.numberOfAlbums = numOfAlbums;
this.albums = new Album[numOfAlbums];
}
// add getters and setters
// example of adding a new album
public void addNewAlbum(Album album){
if(this.numOfAlbums == this.albums.length){
// you need to create a new array with a bigger size, copy the existing data and insert the album
// or whatever you'd like
} else {
this.albums[this.numOfAlbums] = album;
// increment the numOfAlbums
this.numOfAlbums++;
}
}
}
private class Album {
//...
}
You just need to add [] to define that the field is an array.
public class Band {
private int totalAlbums;
private Album[] albums;
//...
}
private class Album {
//...
}
I hope this example helps you.
private Album[] albums; // array of album
private int albumLimit; // limit for album
public Band(int albumLimit) {
this.albumLimit = albumLimit; // initialize limit
this.albums = new Album[albumLimit]; // set limit of album array
}
// here it creates a new Album every time the loop runs
// you can fill the array in other ways too
public void fillAlbum() {
for (int i = 0; i < albumLimit; i++) {
String name = "name_" + i;
int team = i;
albums[i] = new Album(name, team);
}
}
public void printAlbum() {
for (int i = 0; i < albumLimit; i++) {
System.out.println("Name :" + albums[i].getTitulo());
System.out.println("Team :" + albums[i].getTemas());
System.out.println();
}
}
}

How to access the properties of an object contained in an arraylist that is a property of another object

I am trying to reference the properties of an object contained within an array list that is itself the property of another object.
here is a simple version of the code
Item class
public class Item {
String name;
String stat;
int dmg;
public Item(String name, String stat, int dmg) {
this.name = name;
this.stat = stat;
this.dmg = dmg;
}
}
Unit class
import java.util.ArrayList;
public class Unit {
String unitName;
int unitHealth;
int unitMoves;
int unitDmg;
ArrayList<Item> unitInv;
protected Unit(String name, int health, int dmg, int moves, ArrayList<Item> inv) {
unitName = name;
unitHealth = health;
unitDmg = dmg;
unitMoves = moves;
unitInv = inv;
}
}
Game class
import java.util.ArrayList;
public class Game {
public static void main(String[] args) {
Item testItem = new Item("Test Item", "DMG", 10);
ArrayList<Item> unitInv = new ArrayList<>();
Unit unitObj0 = new Unit("Test Unit", 100, 10, 4, unitInv);
unitInv.add(testItem);
}
public void getName() {
for(int i =0; i < unitInv.size(); i++) {
System.out.println(i);
}
}
}
I am trying to figure out how I would specifically reference each of the properties of testItem contained within unitInv. I am wanting to code methods that access the properties of testItem and use them to modify the properties of unitObj0. The point of this is that I will be changing the items contained within unitInv and I will need to be able to write modular code that can access this same information regardless of the item or number of items contained within unitInv.
I have spent a lot of time messing with for loops but I don't understand how to get the loop to access the properties of testItem contained within unitInv not to mention I'm not sure that that would be the appropriate thing to do here. If there is a better modular way to do what I am trying to do here please advise with details if possible.
So your code has the following issues:
unitInv is defined inside of main, hence, it cannot be reached outside of its scope. You must either declare it outside of the method or pass its reference to the method that you are calling.
I don't see where you are calling getName method, but I'm going to assume that it's inside of main.
Try this:
import java.util.ArrayList;
public class Game {
public static void main(String[] args) {
Item testItem = new Item("Test Item", "DMG", 10);
ArrayList<Item> unitInv = new ArrayList<>();
Unit unitObj0 = new Unit("Test Unit", 100, 10, 4, unitInv);
unitInv.add(testItem);
getName(unitObj0);
}
public void getName(Unit unit) {
for( Item item : unit.unitInv ) {
System.out.println(i);
}
}
}
If you want to access every item in the unitInv list of the unitObj0 object you can try this for loop:
for ( Item item : unitObj0.unitInv ) {
// use your individual item here
}
This will allow you to access every item of the ArrayList unitInv which is a property of the unitObj0.

Don't understand lines and how to assign genres to objects in this class

This is the class Painting:
public class Painting {
private String genre;
public Painting() {
}
public Painting (String aGenre) {
genre = aGenre;
}
public String getGenre(){
return genre;
}
}
From this class I was trying to create 4 objects and assign each a genre which I did below.
public class PaintingGenre {
public static void main(String[] args) {
Painting [] p = new Painting [4];
p[0].genre = "Brush";
p[1].genre = "Crayon";
p[2].genre = "Pencil";
p[3].genre = "Watercolour";
}
}
However, genre is private in the java class.. is there a way to assign these genres to the four objects/ paintings without changing the genre from private to public in the java class?
I think I can somehow do that by using these lines in the java class below but I don't know what it means... could you explain these lines for me and tell me if and how I can assign genres to the paintings using these lines?
public Painting (String aGenre) {
genre = aGenre;
}
public String getGenre() {
return genre;
}
Thanks very much!
Without changing the class, the only way to set the value is via the constructor. So you'd initialize any given instance with the value:
p[0] = new PaintingGenre("Brush");
The alternative would be to add a setter to the class:
public void setGenre(String genre) {
this.genre = genre;
}
and call that on an object (if the object has already been initialized):
p[0].setGenre("Brush");
Even if your genre field was public, when you try to assign it in your current code, you would end up with a NullPointerException anyway, because just creating an array of objects does not actually create objects inside it. This is where your constructor comes in.
This function:
public Painting (String aGenre) {
genre = aGenre;
}
is called a constructor. What it does is create a new object and, in this case, take the String called "aGenre" and assign it to the object's genre field. You can use this to fill out the array you created with Paintings with the correct genres.
Painting [] p = new Painting [4];
p[0] = new Painting("Brush");
p[1] = new Painting("Crayon");
p[2] = new Painting("Pencil");
p[3] = new Painting("Watercolour");
The other function you asked about:
public String getGenre(){
return genre;
}
simply returns the genre assigned to the object you call it on. For example:
String str = p[0].getGenre(); // str now has the value "Brush"
str = p[1].getGenre(); // str now has the value "Crayon"
Usually, you don't directly access a field.
The best thing you can do is to implement Getter and Setter, like this:
public Painting (String aGenre) {
genre = aGenre;
}
public String getGenre(){
return genre;
}
With this code, you set the genre at initialization of the object.
But you'd have to edit your assignment:
Painting [] p = new Painting [4];
p[0] = new Painting("Brush");
p[1] = new Painting("Crayon");
p[2] = new Painting("Pencil");
p[3] = new Painting("Watercolour");

Instantiating and Updating Several Objects

Currently I am teaching myself Java but I came across a simple problem but have no one to ask from. From one of the exercises, I wrote a class and write a driver class that instantiates and updates several objects. I am confused by "instantiates and updates several objects." Here is what I mean: So here is my class:
public class PP43Car {
private String make = "";
private String model = "";
private int year;
public PP43Car(String ma, String m, int y)
{
make = ma;
model = m;
year = y;
}
public void setMake(String ma)
{
make = ma;
}
public String getMake()
{
return make;
}
public void setModel(String m)
{
model = m;
}
public String getModel()
{
return model;
}
public void setYear(int y)
{
year = y;
}
public int getYear()
{
return year;
}
public String toString()
{
String result = "Make of the vehicle: " + make +
" Model of the vehicle " + model +
" Year of the vehicle: " + year;
return result;
}
}
Which instantiates make, model and year. Then once I was writing the driver class, the way I began was:
import java.util.Scanner;
public class PP43CarTest {
public static void main(String[] args) {
PP43Car car1;
Scanner scan = new Scanner(System.in);
System.out.println("Enter the model of the vehicle:");
car1.getModel();
}
}
But this class produces error and here is where I am stuck. Do I keep on going with this or is this what is meant by "instantiating and updating several objects?"
import java.util.Scanner;
public class PP43CarTest {
static PP43Car car1;
public static void main(String[] args) {
//Scanner scan = new Scanner(System.in);
car1 = new PP43Car("Millenia", "Mazda", 2011);
}
}
If the above code is correct, then can anyone show me how I can use the Scanner class to actually get the user input and update it that way because I would like to learn that as well?
Well, in your last fragment of code you are indeed instantiating an object, since you are doing:
car1 = new PP43Car("Millenia", "Mazda", 2011);
When you create a new object, you are creating a new instance of the class, so yes, you are instantiaing an object.
But you aren't updating it anywhere, because I think here updating means modifying the object, but you only create the object, not modify it...
Something like this would be an update:
car1.setYear(2013);
Since you are setting a different value for an attribute of the object, you are updating it...
EDIT: Try this code, it can't throw any exception, it's Java basics! I hope it clarifies your doubts...
public class PP43CarTest {
public static void main(String[] args) {
//Declaring objects
PP43Car car1;
PP43Car car2;
PP43Car car3;
//Instantiating objects
car1 = new PP43Car("Millenia", "Mazda", 2011);
car2 = new PP43Car("Aaaa", "Bbb", 2012);
car3 = new PP43Car("Ccc", "Ddd", 2012);
//Updating objects
car1.setMake("Xxx");
car1.setMake("Yyy");
car1.setYear(2013);
//Printing objects
System.out.println("CAR 1: " + car1.toString());
System.out.println("CAR 2: " + car2.toString());
System.out.println("CAR 3: " + car3.toString());
}
}

Categories