这是我的错误指向的代码:
shipX = shipOne.getX();
EDIT2:具体来说,它无法找到shipOne。
Ship对象shipOne在Switch语句内初始化,而不是上述代码之前的十行。我很确定错误是由于在Switch语句中初始化对象而出现的,我不知道如何处理。总共有八个Ship对象通过循环初始化,因此上面的代码需要在Switch语句或If语句中,这两个我确定会导致相同的错误。是否有我可以抛出的异常或导致我的程序运行的东西? Ship对象做在100%的时间内被初始化,因此不用担心。
编辑:我被问到其余的代码,所以这里是:
(这不是全部内容,因为您无法看到退货声明,但其余部分与我的问题无关)。
public static String[][] createFleet()
{
//Initialize Variables
//Ship Variables
boolean isHoriz = true; //Is true if ship is Horizontal, false if Vertical
char ID;
int posX = 0; //Origin of the ship (x coordinate [row])
int posY = 0; //Origin of the ship (y coordinate [column])
int size = 0; //Either 2, 3, or 4
//Associated Variables
Random randomGen = new Random(); //Random number generator
String[][] board = new String[10][10]; //Gameboard, populated with ships
int orientationRand = 0; //If 0, Ship Horizontal. If 1, Ship Vertical
int posRand = 0; //Assigned to posX or posY
int sizeRand = 0; //If 0 <= x < 10, size = 2
//If 10 <= x < 40, size = 3
//If 40 <= x < 100, size = 4
//Create Ships
for (int i = 0; i < 8; i++)
{
//Size
sizeRand = randomGen.nextInt(100);
if (sizeRand < 10)
{
size = 2;
}
else if (sizeRand < 40)
{
size = 3;
}
else size = 4;
//Orientation & Position
orientationRand = randomGen.nextInt(2);
if (orientationRand == 0)
{
//Orientation
isHoriz = true;
//Position (horizontal)
//x position
switch (size)
{
case 2:
posRand = randomGen.nextInt(9);
posX = posRand;
break;
case 3:
posRand = randomGen.nextInt(8);
posX = posRand;
break;
case 4:
posRand = randomGen.nextInt(7);
posX = posRand;
break;
}
//y position
posRand = randomGen.nextInt(10);
posY = posRand;
}
else
{
//Orientation
isHoriz = false;
//Position (vertical)
//x position
posRand = randomGen.nextInt(10);
posX = posRand;
//y position
switch (size)
{
case 2:
posRand = randomGen.nextInt(9);
posY = posRand;
break;
case 3:
posRand = randomGen.nextInt(8);
posY = posRand;
break;
case 4:
posRand = randomGen.nextInt(7);
posY = posRand;
break;
}
}
//Assign Size, Orientation, and Position to each ship
switch (i)
{
case 0:
ID = 'A';
Ship shipOne = new Ship(posX, posY, size, isHoriz, ID);
break;
case 1:
ID = 'B';
Ship shipTwo = new Ship(posX, posY, size, isHoriz, ID);
break;
case 2:
ID = 'C';
Ship shipThree = new Ship(posX, posY, size, isHoriz, ID);
break;
case 3:
ID = 'D';
Ship shipFour = new Ship(posX, posY, size, isHoriz, ID);
break;
case 4:
ID = 'E';
Ship shipFive = new Ship(posX, posY, size, isHoriz, ID);
break;
case 5:
ID = 'F';
Ship shipSix = new Ship(posX, posY, size, isHoriz, ID);
break;
case 6:
ID = 'G';
Ship shipSeven = new Ship(posX, posY, size, isHoriz, ID);
break;
case 7:
ID = 'H';
Ship shipEight = new Ship(posX, posY, size, isHoriz, ID);
break;
}
}
答案 0 :(得分:1)
在您的代码中,“ID”变量未在任何地方声明。您必须在使用之前声明变量。
答案 1 :(得分:0)
在switch或if语句之前将对象初始化为null。我认为这应该可以解决你的问题。
如果发布了整个代码,则可以提供更好的解决方案。