有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

nullpointerexception如何在java中运行具有多个公共类的程序?

我是java的新手。我编写了以下程序:

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();
    }
}

当我运行这个程序时,我得到了java。位于DotCombum的lang.NullPointerException。setup()和dotcombum。startplaying()语句。 我认为类Dotcom和Gamehelper与错误无关,因此没有在这里显示它们。 请帮我解决这个问题。 另外,我想知道是否有可能在不同的源文件中编写类Dotcom和Gamehelper,但在代码中使用它?如果是,怎么办


共 (2) 个答案

  1. # 1 楼答案

    您需要实例化dotcomlist

    ArrayList<Dotcom> dotcomlist = new ArrayList<Dotcom>();
    
  2. # 2 楼答案

    安装程序()中的dotcomlist为空

    加:

    dotcomlist= new ArrayList<Dotcom>();
    

    在设置()的第一行