1

I have created a program, where I have the class dog, with many attributes, together with methods for creating an instance of the class, constructor and getting and setting the attributes. Then I have class CPanel, which is supposed to work as a control panel for the user to access this class, it has array of objects dog and it lets the user allocate the objects into said array and find them, delete them and so on.

However I am having a problem with just said allocation as when creating a dog through said panel, one is supposedly created but right after its done the program continues to start the method Find/CheckDog via the dialogue "Choose dogs name" I understand my code is rather imperfect however I have no clue as to how does the code continue there, also why does it crash right after providing the name of the dog

import java.util.Scanner;

public class friendlycode2 {
  Scanner scan = new Scanner(System.in);

  public class Dog{
    int id;
    boolean deleted;
    String name;
    String breed;
    int age;
    String color; //+standart get/set methods for these atributes
    
    public int GetId(){
        return id;
      }
    public boolean getDeleted(){
        return deleted;
      }
    public void setDeleted(boolean x){
        this.deleted = x;
      }
      public String getName(){
        return name;
      }  

  public Dog(int id, String name, String breed, int age, String color){
  this.name = name; this.breed = breed; this.age = age; this.color=color; this.deleted = false; 
  } 

  }
  public class CPanel{
      int nu2m;
      int Selected;
      Dog obj[ ]= new Dog[10];
  
      public CPanel(){
        System.out.println("Welcome to the dog games");       
        nu2m =0;
  }
  public void SetSelected(int x){
    this.Selected = x;
    }
    public int GetSelected(){ 
      return this.Selected;
    }
    public void CreateDog(){    //the important constructor method
        
        System.out.println("Choose dogs name, breed, age and color \n"); 
        String userInput = scan.nextLine(); 
        String[] InputArray = userInput.split(",", 0);        
        obj[nu2m] = new Dog(nu2m, InputArray[0],InputArray[1],Integer.parseInt(InputArray[2]),InputArray[3]);        
        nu2m ++;   
        System.out.println("New dog created \n");       
        }
  public void DeleteDog(){
    CheckDog();
    obj[Selected].setDeleted(true); 
  }
  public void ShowDogs(){
    for(int i=0;i<obj.length;i++)
    {
      if(obj[i].getDeleted()==false){
        obj[i].toString();}
       else{};
      }
    }  
  public int FindDog(){
    System.out.println("Choose dogs name\n");
    String name = scan.nextLine();
    for(int i=0;i<obj.length;i++)
      {
        if(name ==obj[i].getName()){
          if(obj[i].getDeleted()==false){
        return obj[i].GetId();}
        }
        else{};
    }     
      return -1;
  }
  public void CheckDog(){
    int check = FindDog();
    if(check<0){System.out.println("Dog doesnt exist\n");}
    else{this.SetSelected(check);}    
      }
  }
    public void  mainn()  
  { 
    CPanel NewGame =new CPanel();
    String volba="0";
    System.out.println("Welcome to the dog game\n1: Create new dog\n2: Delete a dogy\n3:Show all dogs\n4:Play the game dogs\n5: Exit\n");
    while(volba!="5"){
    volba = scan.nextLine();
    switch(volba){
    case("1"):
    NewGame.CreateDog();
    case("2"):
    NewGame.DeleteDog();
    case("3"):
    NewGame.ShowDogs();
    case("4"):
    System.out.println("Ending program\n");
    //thegame(NewGame);
    }
    System.out.println("Welcome to the dog game\n1: Create new dog\n2: Delete a dogy\n3:Show all dogs\n4:Play the game dogs\n5: Exit\n");
                    }
   }   
   public static void main(String[] args) {
 friendlycode2 o = new friendlycode2();
 //o.test();
 o.mainn();
  }
}

here is the output

Welcome to the dog game
1: Create new dog
2: Delete a dogy
3:Show all dogs
4:Play the game dogs
5: Exit

1
Choose dogs name, breed, age and color 

d,e,11,d
New dog created 

Choose dogs name

d
Exception in thread "main" java.lang.NullPointerException
        at friendlycode$CPanel.FindDog(friendlycode.java:104)
        at friendlycode$CPanel.CheckDog(friendlycode.java:114)
        at friendlycode$CPanel.DeleteDog(friendlycode.java:87)
        at friendlycode.mainn(friendlycode.java:159)
        at friendlycode.main(friendlycode.java:172)
  • 4
    It would help tremendously — and increase the chance of getting a good answer! — if you could reduce the long code you posted to an [mcve] (MCVE) by removing everything that’s irrelevant. The MCVE should also be properly formatted at a minimum. – Konrad Rudolph Sep 15 '22 at 07:16
  • this should explain (at least) the crashing: https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it – Stultuske Sep 15 '22 at 07:17
  • You are missing `break;` in all your switch/case. Right now, you have fall-trough and all cases will be executed. – knittl Sep 15 '22 at 07:19

2 Answers2

0

this is because some of your obj[i] is null. You need to check for null when iterating obj. e.g:

for(int i=0;i<obj.length;i++){
  if(obj[i]==null){
    // do something here; either skip it or simply break.
  }
fauzimh
  • 594
  • 4
  • 16
  • 2
    It’s generally a *very bad idea* to just blindly pepper your code with `null` checks. Instead, the code should establish preconditions that ensure that `null` objects aren’t created, or can’t be accessed. These checks you’re suggesting are merely hiding underlying logic issues in the code, and lead to unnecessary complexity. – Konrad Rudolph Sep 15 '22 at 07:27
  • You are correct. I simply correct the immediate problem, not the code design. And for this particular case, I would rather use dynamic List rather than array so null check is not even required. – fauzimh Sep 15 '22 at 07:34
0

Your case statement will run createDog immediately followed by deleteDog. It would be evident if you changed your prompts to 'Enter dog name to be created' or 'Enter dog name to be deleted'.

Modify your case statement by adding breaks:

switch(volba){
    case("1"):
        NewGame.CreateDog();
        break;
    case("2"):
        NewGame.DeleteDog();
        break;
    case("3"):
        NewGame.ShowDogs();
        break;
    case("4"):
        thegame(NewGame);
        break; // not really required here
}
Queeg
  • 7,748
  • 1
  • 16
  • 42
  • "not really required here" it's bad practice not to add it. It would be very easy to add another case after, and forget to add the `break`. However, what is definitely not required is the `()` around the case values: `case "1":` is sufficient. Cases need to be compile-time constant expressions; even though `case ((1 + 5) / 2) + (15 / 9):` would be legal, I don't think I have ever seen anything that's not a literal or a constant value used. – Andy Turner Sep 15 '22 at 07:52
  • 2
    Or use the new syntax with an up-to-date Java version, `switch(volba) { case "1" -> NewGame.CreateDog(); case "2" -> NewGame.DeleteDog(); case "3" -> NewGame.ShowDogs(); case "4" -> thegame(NewGame); }` – Holger Sep 15 '22 at 08:21