I'm making a animal farm with each pigs, cows and horses has it's own name.
I choose which place of the array the animal will be placed, and then types the name.
But i can't print the array correctly.
How is it done?
Here is the error:
Exception in thread "main" java.lang.NullPointerException
at Bondegard.main(Bondegard.java:58)
I have only tried with one type of animal, so the other two is not done yet.
This is my code:
import java.util.Scanner;
public class Bondegard
{
static Gris[] grisebinge = new Gris[10];
static Hest[] stall = new Hest[5];
static Ku[] fjos = new Ku[30];
public static void settInnGris(Gris g)
{
Scanner in = new Scanner(System.in);
System.out.println("Hvor vil du sette in grisen? (0-9) ");
int index = in.nextInt();
for(int i=0; i<grisebinge.length; i++)
{
if(grisebinge[index] != null)
{
System.out.println("Plassen er opptatt");
index = in.nextInt();
}
else if(grisebinge[index] == null)
{
System.out.println("Hva heter grisen din?");
Scanner inn = new Scanner(System.in);
String temp = inn.nextLine();
grisebinge[index]=g;
grisebinge[index].setGrisNavn(temp);
break;
}
}
}
static void settInnHest(Hest h) { }
static void settInnKu(Ku k) { }
public static void main(String[]args)
{
Gris g = new Gris();
settInnGris(g);
settInnGris(g);
settInnGris(g);
settInnGris(g);
settInnGris(g);
for(int i=0; i<grisebinge.length; i++)
{
System.out.println(grisebinge[i].getGris());
}
}
}
and my Gris class is
public class Gris {
private String grisHeter;
public String getGris()
{
return grisHeter;
}
public void setGrisNavn(String m)
{
grisHeter=m;
}
}
settInnGris()-method will stop if the user enters 10 taken indices in a row. If you want it to keep repeating until the he enters a vacant index, you should remove the conditioni < grisebinge.length. But if you do that, you should probably also notify the user that there are no more vacant places left if he tries to add an 11th pig. (To avoid an infinite loop)