所以我已经进入了我的Battleships游戏的这个阶段,我已经创建了一个阵列并填充了一个10x10网格我现在想要这样做,以便用户可以输入坐标x,y,z和网格更新到而不是O,解决这个问题的最佳方法是什么。这对于java来说是非常新的。
GRID
public class Grid1 {
public void BattleshipsGrid() {
System.out.println ("Players Board");
char [][] grid = new char [10][10];
//FILL GRID//
for(int outerLoopValue = 0; outerLoopValue<10;outerLoopValue++)
{
for(int innerLoopValue = 0; innerLoopValue<10;innerLoopValue++)
{
grid[outerLoopValue][innerLoopValue]='O';
}
}
//END OF FILL GRID//
//DRAW GRID//
for(int outerLoopValue = 0; outerLoopValue<10;outerLoopValue++)
{
System.out.println("");
for(int innerLoopValue = 0; innerLoopValue<10;innerLoopValue++)
{
System.out.print(grid[outerLoopValue][innerLoopValue]+" ");
}
}
}
}
主要游戏
public class Game {
public static void main (String args[]) {
//Calling Player grid
Grid1 CPUGrid = new Grid1();
Grid1 PGrid = new Grid1();
System.out.println("Welcome to Battleships");
System.out.println("Please choose the co-ordinates for your ships");
System.out.println("");
System.out.println("");
CPUGrid.BattleshipsGrid();
}
}
答案 0 :(得分:1)
如果将grid
转换为实例变量,您将会更容易。然后,您可以直接从Game
进行编辑。有关实例变量的更多信息,请查看this问题。
作为一个注释,虽然public
实例变量可以用于学习Java的机制,但它们对于大型项目来说并不实用;更多信息here。
public class Grid1 {
public char [][] grid = new char [10][10];
public Grid1() {
//initialize grid
for(int outerLoopValue = 0; outerLoopValue<10;outerLoopValue++)
{
for(int innerLoopValue = 0; innerLoopValue<10;innerLoopValue++)
{
grid[outerLoopValue][innerLoopValue]='O';
}
}
}
public void PrintGrid() {
for(int outerLoopValue = 0; outerLoopValue<10;outerLoopValue++)
{
System.out.println("");
for(int innerLoopValue = 0; innerLoopValue<10;innerLoopValue++)
{
System.out.print(grid[outerLoopValue][innerLoopValue]+" ");
}
}
}
}
public class Game {
public static void main (String args[]) {
//Calling Player grid
Grid1 CPUGrid = new Grid1();
Grid1 PGrid = new Grid1();
System.out.println("Welcome to Battleships");
System.out.println("Please choose the co-ordinates for your ships");
Scanner s = new Scanner(System.in);
System.out.println("X coord: ");
int x = System.out.println(s.nextInt());
System.out.println("Y coord: ");
int y = System.out.println(s.nextInt());
PGrid.grid[x][y] = 'S'
}
}
答案 1 :(得分:0)
我相信你只需要坐标x,y,因为你只有一个10x10网格。
继续,基于这个假设。
从用户处获取输入,然后将O更改为S,如下所示
System.out.println("Please enter the X location [1-10]");
int x = Integer.parseInt(System.console().readLine()) - 1;
System.out.println("Please enter the Y location [1-10]");
int y = Integer.parseInt(System.console().readLine()) - 1;
//Assuming the user enters an integer only.
//You may want to implement a check to ensure this
grid[x][y] = 'S';