I am learning java and was trying some stuff. This is what I am trying to do.
I am trying to create an table of an array of an object. e.g. I am creating an object called animal by which i can add any number of animal and its breed on user choice.
package tt;
import java.util.Scanner;
public class animal {
String aname;
String abreed;
public animal() {
mainprog aa = new mainprog();
System.out.printf("eneter name of your %s..\n", aa.Animalcat);
Scanner name = new Scanner(System.in);
aname = name.nextLine();
System.out.printf("eneter breed of your %s..\n", aa.Animalcat);
Scanner breed = new Scanner(System.in);
abreed = breed.nextLine();
}
public String getbreed() {
return abreed;
}
public String getname() {
return aname;
}
}
So the main program ask for how many animals I want to add.
package tt;
import java.util.Scanner;
public class mainprog {
public static String Animalcat;
public static void main(String[] args) {
System.out.println("How many animals you want to add..");
Scanner an = new Scanner(System.in);
int animalNumbers = an.nextInt();
animal[][] addAnimal = new animal[animalNumbers][1];
animaltype[] at = new animaltype[animalNumbers];
for (int i = 0; i < animalNumbers; i++) {
at[i] = new animaltype();
Animalcat = at[i].getAnimalType();
for (int j = 0; j < 1; j++) {
addAnimal[i][j] = new animal();
}
}
Display(addAnimal, at);
}
public static void Display(animal x[][], animaltype y[]) {
System.out.println("Your animals are..");
for (int m = 0; m < x.length; m++) {
System.out.printf("Following are the name and the breed of %s ",
y[m].getAnimalType());
System.out.println();
for (int n = 0; n < x[m].length; n++) {
System.out.printf(" %s", x[m][n].aname);
System.out.printf(" %s", x[m][n].abreed);
System.out.println();
}
}
}
}
package tt;
import java.util.Scanner;
public class animaltype {
String animalType;
public animaltype() {
System.out.println("What kind of animal you want to add..");
Scanner at = new Scanner(System.in);
animalType = at.nextLine();
}
public String getAnimalType(){
return animalType;
}
}
The issue I have here is I can ask for how many types of animals I want to add but I can't control how many animals of that type I want to add. While adding animal I can only add 1 number of animal manually by declaring it as [1] and can't by user input.
addAnimal = new animal[animalNumbers][1];
The problem in if I can do that by declaring animal[][] addAnimal = null; and then later initialize it with like:
animal[][] addAnimal = new animal[animalNumbers][animaltypenumbers];
But I get NullPointerException all time. Is there anyway I can have this done?