I keep getting NullPointerException in the following code.
The exception appears at this line System.out.println(myHeros.toString());
public class test {
public static void main(String[] args) {
Hero A = new Hero("Archer");
Hero B = new Hero("Bacca");
Hero C = new Hero("Chester");
Hero D = new Hero("Teemo");
Hero E = new Hero("Garen");
MyStack myHeros = new MyStack(10);
System.out.println(!(A instanceof Hero)); // Output: false;
boolean debug = true;
try {
myHeros.push(A);
if(debug) {
System.out.println("lalala");
}
}
catch(notAHeroException e) {
//e.printStackTrace();
}
System.out.println(myHeros.toString()); //This is the line that throws nullPointerException;
System.out.println(myHeros.getTop()); //(Debug) Output: 1, the Hero was actually pushed into myHeroStack;
}
}
This is the class containing the toString method. I really cannot see where possibly can cause a NullPointerException.
public class MyStack implements Stack{
public Hero[] myHeroStack; //instance field; can be from this class to the whole world;
int top; //The combination of these instance fields represent all you know about your object and all you can use about your object;
public MyStack() {
myHeroStack = new Hero[5];
top = 0;
}
public MyStack(int numOfHero) {
myHeroStack = new Hero[numOfHero];
top = 0;
}
@Override
public void push(Hero h) throws notAHeroException{
//check the input;
boolean checkType = !(h instanceof Hero);
if (checkType) { //if (!(h instanceof Hero))
throw new notAHeroException("Check again what did you add?!");
}
else {
myHeroStack[top] = h;
top = top + 1;
}
}
@Override
public void pull(Hero g) throws emptyStackException { //check whether the element you want to throw actually exist;
//check whether the element exist
if(myHeroStack[top - 1] == null) {
throw new emptyStackException("You do have this hero in you stack!");
}
else {
Hero heroToPull = myHeroStack[top - 1];
System.out.println(heroToPull.getName());
myHeroStack[top - 1] = null;
top = top -1;
}
}
@Override
public void peek(Hero p) {
System.out.println(p.getName());
}
public int getTop() {
return top;
}
public String toString() {
//check whether the stack is null
if(top == 0) {
return ("You hero stack is empty");
}
else {
String AllMyHero = "";
for(Hero hero: myHeroStack) {
AllMyHero = AllMyHero + "All my hero is " + hero.getName()+ "%n"; //hero is null point
}
return AllMyHero;
}
}
}
This is the Hero class, which is quite simple.
public class Hero {
private String name;
public Hero(String name) {
this.name = name;
}
}
Thank you for all who takes a look at this question!