您好,我目前正在为我的 Java 编程课程的考试做作业。现在我正试图让这个程序运行没有错误。谁能帮我理解我做错了什么?我有这段代码,但遇到了 NullPointerException:
java.lang.NullPointerException 在 sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 在 sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) 在 sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) 在 java.lang.reflect.Method。在 edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272) 调用(未知来源)
import java.util.Random;
import java.util.Scanner;
public class BattleShip {
// Board size
int boardxlength = 5;
int boardylength = 5
//ships
Ship submarine;
Ship destroyer;
Ship battleship;
// Random number function
Random random = new Random();
// Begin Main
public void main(String args[]) {
// create Ships
SetupShips();
System.out.println(submarine.length);
} // end Main function
// Create Ships function
public void SetupShips() {
submarine = new Ship("submarine", random.nextInt(boardxlength), random.nextInt(boardylength), 2);
destroyer = new Ship("destroyer", random.nextInt(boardxlength), random.nextInt(boardylength), 3);
battleship = new Ship("battleship", random.nextInt(boardxlength), random.nextInt(boardylength), 4);
}
/**
* **************************************
*/
/* CLASSES
/******************************************/
public class Ship {
String type;
int row;
int col;
int length;
//Constructor
public Ship(String strtype, int intx, int inty, int intlength) {
type = strtype;
row = intx - 1;
col = inty - 1;
length = intlength;
}
} // end Ship Class
}// end main class