我是Java新手,也是创建战舰游戏的练习。显然,有两个游戏板(每个游戏一个),每个游戏板将分配三个游轮。那么,我的想法是制作一个“GameBoard”类,其中包含一个“船”类,所以我可以创建新的船只,这些船只将被放置在它们的板上。这是我到目前为止所做的:
public class GameBoard {
int columnCount = 7;
int rowCount = 7;
int spaceCount = rowCount*columnCount;
private class ship {
private String name;
private void setName(String newName) {
name = newName;
}
}
}
现在我的问题是如何在游戏板中调用新船。要创建一个新的董事会,我会这样做:
GameBoard player1 = new Gameboard();
但是我从哪里去?它会是这样的吗?
player1.ship ship1 = new player1.ship();
我的直觉告诉我这是非常错误的,我只是不确定该怎么做。谢谢你的帮助!
答案 0 :(得分:3)
你可以这样做。
public class GameBoard {
int columnCount = 7;
int rowCount = 7;
int spaceCount = rowCount*columnCount;
ship s;
}
public class ship {
private String name;
private void setName(String newName) {
name = newName;
}
}
然后
GameBoard gb = new GameBoard();
gb.s = new ship();
答案 1 :(得分:0)
您的意思是如何从外部类中实例化新船?在这种情况下,您可以简单地写
ship t = new ship();
答案 2 :(得分:0)
如果您想从外层实例发货,您应该:
如下:
public class GameBoard {
int columnCount = 7;
int rowCount = 7;
int spaceCount = rowCount*columnCount;
public static class ship {
private String name;
private void setName(String newName) {
name = newName;
}
}
}
然后你可以这样做:
ship1 = new GameBoard.ship();
答案 3 :(得分:0)
Ship是一个私有类,所以它只能由GameBoard修改。您可以通过以下方式创建船舶:
public class GameBoard {
int columnCount = 7;
int rowCount = 7;
int spaceCount = rowCount*columnCount;
ship _ship = new ship();
private class ship {
private String name;
private void setName(String newName) {
name = newName;
}
}
public ship getShip(){return _ship);
您必须通过player.getShip().setName("USS SOMETHING")
或者更好
public class GameBoard {
int columnCount = 7;
int rowCount = 7;
int spaceCount = rowCount*columnCount;
ship _ship;
public GameBoard(String shipName){
_ship = new ship();
_ship.setName(shipName);
}
private class ship {
private String name;
private void setName(String newName) {
name = newName;
}
}
在创建GameBoard时,您可以在其中设置船名。 GameBoard player1 = new GameBoard("USS SOMETHING")