繁体   English   中英

Java中的Null指针异常。 (数组中断循环?)

[英]Null Pointer Exception in Java. (Broken for loop with array?)

因此,我已经阅读了其他人的其他问题,但找不到适合我的解决方案。 我正在学习Java,因此决定制作一个基于控制台的简单战舰游戏,以测试一些基本的Java原理和实现。 就在程序的开始,我收到了NullPointerException错误。

这是我的代码到错误点为止的样子:

public class Battleship {

public static String[] xValues = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"};
public static String[] shipNames = {"patrol", "sub", "cruiser", "battle", "carrier"};
public static boolean isCollision = true;

//Create the Ship Array
public static Ship[] ships = new Ship[5];



public static void main(String[] args) {

    //Welcome the User
    System.out.println("Welcome to Battleship!\nLet's see how many tries it take to sink the ships!");

    //Now, let's make 5 kinds of ships: Patrol Boat, Submarine, Cruiser, Battleship, Carrier. Each has a different size.
    for (int i = 0; i < shipNames.length; i++){
        ships[i].setName(shipNames[i]);
    }

我唯一想到的可能是封装问题,因为数组shipNames的静态值不在main方法之外。 但是,将其放置在main方法中也不能解决该问题。 我以为垃圾回收可能是在main方法启动时发生的,并且因为数组为空而破坏了数组,但是这也没有用,因为调试器显示shipNames.length = 5我感到困惑。 这里有什么想法吗? 提前致谢。

您需要为阵列的每个插槽创建一个新的Ship对象。 请记住,对象的默认值为null

for (int i = 0; i < shipNames.length; i++){
        ships[i] = new Ship();
        ships[i].setName(shipNames[i]);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM