0

I am getting a null pointer exception on my nameA = view.getHumanName(nameB); line in my model class. I am trying to establish nameA using the getHumanName method from the view class. I also attempted to add in this.view = view to the model constructor but that does not fix the issue. Why am I getting this error in this instance?

Model class and instance variable:

   public Model(Dice die){
      nameB = "Toby";
      nameA = view.getHumanName(nameB);
      p1 = new Player(nameA);
      p2 = new Player(nameB);
      this.die = die;
   }
}

Method in View class:

public String getHumanName(String compName){
   System.out.println("Enter a name for the human player: ");
   String humanName = scan.nextLine();
   while(humanName.equals(compName) || humanName.trim().isEmpty()){
        System.out.println("The human player cannot have the same name as the computer player or be blank. Enter a new name for the human player: ");
        humanName = scan.nextLine();
   }
   return humanName;
}
  • 1
    Where is your object initialization for the View ref: https://www.javaworld.com/article/3040564/learn-java/java-101-class-and-object-initialization-in-java.html – mallikarjun Apr 23 '18 at 14:05
  • Your view isn't yet instantiated when you call `view.getHumanName`, You must create the view object before using it (`view = new View ()`) –  Apr 23 '18 at 14:06
  • Most definalty a duplicate. there is 2 easy ways to fix it. One is intatiate view, 2nd is make the method static. I assume you are learning about MVC. Also read up about the role of the controller. – Noldy Apr 23 '18 at 14:08
  • @MehdiB. Yeah I tried that and am still getting the error i am not sure why – T.Jones8910 Apr 23 '18 at 14:09
  • Side note: `Scanner.hasNextLine()` must return true before you can safely call `Scanner.getNextLine`. – DwB Apr 23 '18 at 14:10
  • 1
    have you initialized the scanner object, if not `scan = new Scanner(System.in)` – Roushan Apr 23 '18 at 14:11
  • As @Roushan said have you initialized the scan and could you post the stack trace by edit the question. – mallikarjun Apr 23 '18 at 14:13
  • For future reference, you should post a [mcve] for any question. This means that your code should produce the same exact error that you are asking about. The code in this question has many compiler errors so we cannot see the NPE you need help with. – Code-Apprentice Apr 23 '18 at 14:16
  • @Roushan Yeah i initialize the scanner in my view class so that isn't the issue – T.Jones8910 Apr 23 '18 at 14:22

1 Answers1

2

You never assign anything to view, so by default it is initialised as null. Try putting the following in your constructor:

view = new View();
Benjamin James Drury
  • 2,353
  • 1
  • 14
  • 27