Java: Making classes with arrays and using those arrays in another class - java

I've looked around and haven't found an answer to exactly what I am asking so here it is:
I'm new to Java and I need to make a class that has 3 arrays which can be called from another class. I am lost because I don't know how to "properly" create the instance so that it can be called from the other class without inheritance.
public class Book {
int[] Book0 = new int[7];
int[] Book1 = new int[4];
int[] Book2 = new int[3];
public Book {
Book0 = new int[] {1,2,3,4,5,6,7};
Book1 = new int[] {};
Book2 = new int[] {};
}
}
public class Catalogue {
public Catalogue{
}
}
In class Catalogue I'm not sure how to call the instance in class Book. Do I need to change class Book and put "this"? If so, is it this() or this.____? Or do you do that in class Catalogue?

You want to encapsulate your fields with getters and setters and give your getters public access type so you can access your array outside of the object, and package.
public class Book {
int[] Book0;
int[] Book1;
int[] Book2;
public Book {
Book0 = {1,2,3,4,5,6,7};
Book1 = new int[4];
Book2 = new int[3];
}
public int[] getBook0(){
return Book0;
}
public int[] getBook1(){
return Book1;
}
public int[] getBook2(){
return Book2;
}
}
public class Catalogue {
public Catalogue{
Book book = new Book();
int[] tempArray = book.getBook0();
}
}

You need to create an object of the class and the you can use that object to call methods or a constructor.
Book book = new Book();

You would probably want to instantiate Book and use the instance.
In Catalogue class (or any other class that uses Book):
Book b = new Book();
b.Book0; // {1,2,3,4,5,6,7}
b.Book1; // {}
b.Book2; // {}
Also you should declare the arrays as explicitly public, to indicate everyone can see and modify them.
If this Book object will have further functionalities (methods it implements) you should probably not use it like this but declare the arrays as private, not allowing access to any other class, and using getters/setters instead (think if you really need direct access).
By the way, in your code you initialize the three arrays with empty arrays with sizes 3, 4, and 7. These initializations are overriden by the constructor (which resets the arrays).

I'm not sure, but if i understood you, you want do something like that:
public class Book {
// private fields : Remmember, in java + OOP class members should be private
private String[] page0;
private String[] page1;
private String[] page2;
public Book(int sizeOfPage0, int sizeOfPage1, int sizeOfPage2) {
page0 = new String[sizeOfPage0]; // Argument inside [] sets array size
page1 = new String[sizeOfPage1];
page2 = new String[sizeOfPage2];
}
// Getters
public String[] getPage0() {
return page0;
}
public String[] getPage1() {
return page0;
}
public String[] getPage2() {
return page2;
}
}
public class Catalogue {
private Book[] books;
public Catalogue(Book[] books) {
this.books = books;
}
public Book[] getBooks() {
return this.books;
}
}
public class MyApp {
// entrypoint of the application
public static void main(String[] args) {
Book book1 = new Book(2, 1, 1);
book.getPage0()[0] = "In some place of 'La mancha' which I do not want remember";
book.getPage0()[1] = "lives some 'hidalgo' ... etc";
book.getPage1()[0] = "Sancho Panza as squire of Don Quijote";
Book book2 = new Book(1, 3, 1);
// ... something similar...
Book[] books = {book1, book2};
Catalogue catalogue = new Catalogue(books);
System.out.println(catalogue.getBooks()[0].getPage0()[0]);
}
}
Remember to take each class into a separated file or get only one public class and the rest default per file

Related

Java: how can I put new object into array of objects of its class inside a constructor function? Is it possible?

everyone! I'm total noob in Java and in programming in general and I want to implement CarBrand class with its' inner Model class (let there be no more than 4 models for each brand). For example:
public class CarBrand {
public String brand;
public Model[4] models;
public int curIndex = 0;
public CarBrand(String name) {
brand = name;
Model[] models = new Model[4];
}
public class Model {
public String modelName;
public Model(String name) {
modelName = name;
models[curIndex] = this;
curIndex = curIndex + 1;
}
}
}
I want to make new instance of CarBrand and its new Model (and add this model into models array of new instance of CarBrand) this way:
public class App {
public static void main(String args[]) {
CarBrand subaru = new Auto("Subaru");
CarBrand.Model legacy = subaru.new Model("Legacy");
System.out.println(subaru.models[0]);
}
}
But unfortunately running App finishes with error:
Exception in thread "main" java.lang.NullPointerException: Cannot store to object array because "<parameter1>.models" is null
What is the reason behind that? Is there a way to add a new model in brand's models array? I suppose, the object wasn't created yet, that's why there is an error. How far am I from the truth?
Your syntax is generally incorrect: you would need
public Model[] models; // not Model[4]
public int curIndex = 0;
public CarBrand(String name) {
brand = name;
models = new Model[4]; // not Model[]
}

how to retrieve an array into one class from a different class

I have a class where I made an array of the planets.
private final static Planet[]
{
new Planet("Mercury"),
new Planet("Venus"),
new Planet("Earth"),
new Planet("Mars"),
new Planet("Jupiter"),
new Planet("Saturn"),
new Planet("Uranus"),
new Planet("Neptune")
};
and I need to retrieve it into another class.
public float getPlanetMass()
{
}
How exactly would I go about this?
You can have a public method in a class to return the planets and another class that will call that method to get the list. Something like below :
public class Test {
private Planet[] getPlanets(){
Planet[] planets = new Planet[8];
int index = 0;
for(String name : Arrays.asList("Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune")) {
planets[index++] = new Planet(name);
}
return planets;
}
static class PlanetClient{
public static void main(String args[]) {
Test test = new Test();
Planet[] planets = test.getPlanets();
System.out.println("Planets are " + Arrays.toString(planets));
}
}
class Planet {
String name;
Planet(String name){
this.name = name;
}
#Override
public String toString() {
return this.name;
}
}
}
There are a lot of ways to do this but instead of creating an array you could create an Enum called Planet or even an enum called StandardPlanet or TerrestialPlanet that implements an interface called Plant. This way the enum uses the multiton pattern, you can reference these elements publicly, and you're not creating non-private mutable objects.
public interface Planet {
}
public enum TerrestialPlanet implements Plant {
EARTH,
MARS,
// etc
}
Planet planet = TerrestialPlanet.EARTH;

Java - Custom type nested in class

I am once again asking for technical support.
I need to define a custom type inside a class, I've done it like this:
public class MainClass {
private class CustomType {
public byte[] varA;
public int varB;
public CustomType() {
varA = new byte[3];
varB = 13;
}
}
private CustomType[] myArray;
public MainClass() {
myArray = new CustomType[1024]
System.out.println(this.CustomType[0].varB);
}
}
When I run it throws a NullPointerException at System.out.println(this.CustomType[0].varB);
I've tested if myArray gets properly initialized with 1024 elements and it does, however I can't seem to access them.
I just moved from C++ to Java so I'm still getting used to it, am I missing something blatant?.
You only create an array without any objects, so this.CustomType[0] is null.
You should add the objects to the array:
public MainClass() {
myArray = new CustomType[1024]
for (int i =0; i<myArray.length;i++ {
myArray[i] = new CustomType();
}
System.out.println(this.myArray[0].varB);
}
Also you should make the member of CustomType private and access it via getter and setter.
Two things,
You must instantiate CustomType.
CustomType does not need access to MainClass.this so you can make it static.
So
public class MainClass {
private static class CustomType {
public byte[] varA;
public int varB;
public CustomType() {
varA = new byte[3];
varB = 13;
}
}
private CustomType[] myArray;
public MainClass() {
myArray = new CustomType[1024];
for (int i = 0; i < myArray.length; ++i) {
this.CustomType[i] = new CustomType();
}
// Or
Arrays.setAll(myArray, CustomType::new);
System.out.println(this.CustomType[0].varB);
}
}
Not making it static stores a MainClass.this in every CustomType instance which is unnecessary overhead.
Arrays in java are objects. The following line of the code you posted creates an array of 1024 elements where each and every element is null.
myArray = new CustomType[1024];
If you want to place actual objects in the array, named myArray, you need to create instances of class CustomType and assign them to elements of the array, for example:
CustomType instance = new CustomType();
myArray[0] = instance;
Then you can execute the following line of code and it will not throw NullPointerException.
System.out.println(myArray[0].varB);
Here is the full code to get the value of varB. In which you can avoid declaring CustomType[] myArray
public class Test
{
private static class CustomType
{
public byte[] varA;
public int varB;
public CustomType() {
varA = new byte[3];
varB = 13;
}
}
public static void main(String... args)
{
System.out.println(new CustomType().varB);
}
}
The solution is to add some elements to that array. See the below steps for more information.
constructor will be invoked, when you create the object of that class
And then you created an empty array of CustomType with size 1024 and trying to access the first element which does not exist(default is null) and trying to perform operations on that null reference. So you are getting the NullPointerException.

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.

Better way to call common method on randomly selected object in java

Nice day to everybody.
I have an abstract class with the method runRandomExercise(), and several classes that extends it to add different kind of exercise.
I now want to chose a random type exercise, so I need to randomly choose one of the classes, and call runRandomExercise() on that.
For now I am manually coding this, which is not the very best solution I think. However, I can’t store just the classes in the array since the class type is different, and if I use object[] I can’t call the runRandomExercise() method. Any smart way to handle this?
Here is my code till now. It works, but it’s gonna be a pain to add other classes...
/*Specific classes that extend abstract class TrainingClass with the runRandomExercise() method*/
private MatheMagic mMathMag;
private Mnemonics mMnemonics;
private String[] mTrainingClasses;
/*Initialize classes*/
mMathMag = new MatheMagic();
mMnemonics = new Mnemonics();
/*Manually store classe names*/
mTrainingClasses = new String[2];
mTrainingClasses[0] = "mMathMag";
mTrainingClasses[1] = "mMnemonics";
/*Return random exercise*/
public String[] RandomExercise() {
Random aGenerator = new Random();
/*Get random class name*/
int rnd = aGenerator.nextInt(mTrainingClasses.length);
String aChosen = mTrainingClasses[rnd];
String[] aRes = new String[2];
if (aChosen == "mMathMag") {
aRes = mMathMag.runRandomExercise();
} else if (aChosen == "mMnemonics") {
aRes = mMnemonics.runRandomExercise();
}
return aRes;
}
EDIT
Here is how TrainingClass is defined:
/** Common interface for all exercises */
public interface Exercise {
public String[] run();
}
/** Common interface for all training classes */
public abstract class TrainingClass {
private Random mRandGen = new Random();
public ArrayList<Exercise> mExerciseTypes = new ArrayList<Exercise>();
/** Run a random exercise */
public String[] runRandomExercise() {
int i = mRandGen.nextInt(mExerciseTypes.size());
return mExerciseTypes.get(i).run();
}
}
/*Specific training class*/
public class MatheMagic extends TrainingClass {
public MatheMagic() {
class SomeExercise implements Exercise {
public String[] run() {
String[] mRes = new String[2];
mRes[0] = "Question type 1";
mRes[1] = "Answer type 1";
return mRes;
}
}
class SomeOtherExercise implements Exercise {
public String[] run() {
String[] mRes = new String[2];
mRes[0] = "Question type 2";
mRes[1] = "Answer type 2";
return mRes;
}
}
SomeExercise mN = new SomeExercise();
SomeOtherExercise mS = new SomeOtherExercise();
mExerciseTypes.add(mN);
mExerciseTypes.add(mS);
}
}
Easy solution is to create an interface with the common method and have all your classes extend it.
Create a collection or array of that type instead of Object; you can simply iterate through or randomly select and call the method you want.
It feels like a Command pattern from GoF to me.
public interface Exercise {
void execute();
}
Now your classes do this:
public class MatheMagic implements Execise {
public void execute() {
// special logic here.
}
}
Then you can do this:
int numExercises = 1;
Exercise [] exercises = new Exercise[numExercises];
exercises[0] = new MatheMagic();
for (Exercise exercise : exercises) {
exercise.execute();
}
Yes, yes you can store all those Classes in an array and then call them at random. How? Create an interface and in all your classes derive from that interface. That way you can invoke based on interface, and not on implementation.

Categories