无法在不重新运行方法的情况下保存 Java 中方法的返回值

问题描述 投票:0回答:3

对于编码来说是全新的,如果这是一个基本问题,很抱歉。我正在做一项作业,用 Java 编写游戏战舰的代码。

我正在使用一种方法让用户输入坐标,然后将这些坐标保存为数组以在另一种方法中使用。我知道方法中的变量不会保存。

因此,我为该方法创建了一个返回值,然后在我的主类中创建了一个新变量并设置为该方法的返回值。

public static char[][] player1ships() {
  System.out.println("PLAYER 1, ENTER YOUR SHIPS' COORDINATES.");
  Scanner input = new Scanner(System.in);
  char[][] player1 = new char[5][5];
  for (int i = 0; i < 5; i++) {
    for (int j = 0; j < 5; j++) {
      player1[i][j] = '-';
    }
  }
  for (int i = 1; i <= 5; ) {
    System.out.println("Enter location for ship " + i);
    int a = input.nextInt();
    int b = input.nextInt();
    if ((a >= 0 && a < 5) && (b >= 0 && b < 5) && (player1[a][b] == '-')) {
      player1[a][b] = '@';
      i++;
    } else if ((a >= 0 && a < 5) && (a >= 0 && b < 5) && (player1[a][b] == '@'))
      System.out.println("You can't place two or more ships on the same location");
    else if ((a < 0 || a >= 5) || (b < 0 || b >= 5))
      System.out.println("You can't place ships outside the " + 5 + " by " + 5 + " grid");
  }
  return player1;
}

我想运行该方法,以便用户输入坐标,然后保存返回数组以供稍后使用。但是,当我运行该程序时,它似乎运行该方法两次,因为输出提示用户完成 2 个“输入位置”周期。

当我在末尾添加测试行时,它确实在索引数组中打印了正确的符号,因此它似乎确实保存了更新的数组。

那么如何将返回值保存为变量而不再次运行和打印整个方法?

    public static void main(String[] args) {
        char [][] strike = player1ships();
                
        
        player1ships();

        
        //test to see if array updated
        System.out.println(strike[0][0]);
        
    }
}

这是程序运行的结果...并且执行了两次而不是一次的player1ships方法。

showing how it prompts user through two cycles before printing out the last line

java arrays variables methods return-value
3个回答
2
投票

如果您调用一个方法但不对其返回值执行任何操作,Java 不会抱怨,因此您实际上调用了该方法两次:

player1ships()

char [][] strike = player1ships();

您可以简单地删除 
player1ships();

的第二次调用(没有赋值的调用),因为您不使用它的结果。

    


0
投票
//player1ships();

public static void main(String[] args) { char [][] strike = player1ships(); //This line of yours is superfluous and should be commented out



0
投票

这是我更新的代码:

//test to see if array updated System.out.println(strike[0][0]); }

© www.soinside.com 2019 - 2024. All rights reserved.