-2

I'm a newbie to java. I have written the following program :

import java.util.ArrayList;
import java.io.*;
import java.util.*;



public class dotcombust{
    GameHelper helper=new GameHelper();
    ArrayList<Dotcom> dotcomlist;
    int nofguess=0;

    private void setup(){    
        Dotcom one =new Dotcom();
        dotcomlist.add(one);
        Dotcom two= new Dotcom();
        dotcomlist.add(two);
        Dotcom three= new Dotcom();
        dotcomlist.add(three);

        for(Dotcom obj : dotcomlist)
        {
            obj.setname();
            ArrayList<String> loc= helper.placeDotCom(3);
            obj.setlocation(loc);
        }
    }

    private void startplaying(){    
        while(!dotcomlist.isEmpty())
        {
            nofguess++;
            String guess=helper.getUserInput("Enter a guess ");

            checkuser(guess);
        }
        finish();
    }

    private void checkuser(String guess){    
        String result="miss";
        for(Dotcom obj : dotcomlist)
        {
            result=obj.checkyourself(guess);
            if(result.equals("kill"))
            {
                System.out.println("You killed " + obj.name);
                dotcomlist.remove(obj);
                break;
            }
            else if(result.equals("hit"))
            {
                break;
            }
       }

       if(result.equals("hit") || result.equals("miss"))
       {
           System.out.println(result);
       }
    }

    private void finish(){
        System.out.println("You took " + nofguess + "guesses. If they are below 10, congrats. Otherwise you suck balls. No offense.");
    }

    public static void main(String[] args){
        dotcombust game;
        game=new dotcombust();
        game.setup();
        game.startplaying();
    }
}

When i run the program, i'm getting java.lang.NullPointerException at dotcombust.setup() and dotcombust.startplaying() statements. I thought that the classes Dotcom and Gamehelper are not related to the error and hence did not display them here. Please help me to fix the problem. Also, i wanted to know if it was possible to write the classes Dotcom and Gamehelper in different source file but use it in this code? If so how?.

Berin Loritsch
  • 11,400
  • 4
  • 30
  • 57
Ganesh Biradar
  • 41
  • 1
  • 1
  • 8

2 Answers2

2

You need to instantiate the dotcomlist.

ArrayList<Dotcom> dotcomlist = new ArrayList<Dotcom>();
Joopkins
  • 1,606
  • 10
  • 16
1

dotcomlist is null in setup()

add:

dotcomlist= new ArrayList<Dotcom>();

at the 1st line of setup()

Gavriel
  • 18,880
  • 12
  • 68
  • 105