我的程序遇到以下问题。 它是一个“连接四”Java 控制台应用程序。 当启动我的程序时,我重置了 3 件事。
- 多维字符数组
公共(public)最终 int 行 = 8,列 = 8;
public char[][] board = new char[行][列];
我用 for 循环重置它,用字符“.”覆盖每个数组字段,这是我的默认板纹理。
public char[][] resetBoard() {
// for loops cycle through every array field
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
board[i][j] = '.';
}
}
return board;
}
整数数组
public int[] nums = new int[columns];
我使用变量 i 通过 for 循环重置它,因为我只需要一个包含列长度的数组,该数组只是从 1 开始计数。使用它是为了让用户知道他选择的是哪一列。就像国际象棋“A6”一样,除了没有字母。
public int[] resetNums() {
for (int i = 0; i < nums.length; i++) {
nums[i] = i + 1;
}
return nums;
}
整数
public int roundCounter = 0;
整数记录当前游戏已经进行了多少轮。我希望在播放时打印它。
public int resetRoundCounter() {
// Resetting Round Counter, by initializing it to 0
return roundCounter = 0;
}
我将它们重置为如下所示:
gameMain main = new gameMain();
gameMode mode = new gameMode();
gameCheck check = new gameCheck();
main.board = main.resetBoard();
main.nums = main.resetNums();
check.roundCounter = check.resetRoundCounter();
我的问题是打印游戏板时,nums 数组和圆形计数器似乎都不起作用。 游戏板完全是空白的。 nums 数组只有 0,并且循环计数器保持为 0。 在主方法中运行代码时,它比通过类等运行代码效果更好。
我的打印方法:
public void printBoard() {
gameMain main = new gameMain();
gameCheck check = new gameCheck();
// Printing number array with space in between the elements
for (int i = 0; i < main.nums.length; i++) {
System.out.print(main.nums[i] + " ");
}
// Printing the round count next to the number array
System.out.println(" Round " + check.getRoundCounter());
for (int i = 0; i < main.rows; i++) {
for (int j = 0; j < main.columns; j++) {
System.out.print(main.board[i][j] + " ");
}
System.out.println();
}
for (int i = 0; i < main.nums.length; i++) {
System.out.print(main.nums[i] + " ");
}
System.out.println("\n");
}
我真的需要一些帮助,因为我整夜没睡。最初是因为我在编程时感到非常有趣,现在它变得令人沮丧。
感谢您的阅读并提前致谢!
最佳答案
我认为您所发生的情况与您正在使用的对象的引用有关。您正在混合两种不同的工作方式,我给您举个例子:
您可以使用“roundCounter”的引用并对其进行处理:
public void resetRoundCounter() {
// Resetting Round Counter, by initializing it to 0
roundCounter = 0;
}
或者您可以返回它,如下所示:
public int resetRoundCounter() {
// Resetting Round Counter, by initializing it to 0
return 0;
}
在第一种情况下,您必须像这样调用该函数:
resetRoundCounter(); //this function changes the value of your variable.
在第二种情况下,您必须像这样调用该函数:
roundCounter = resetRoundCounter();
您可以选择您喜欢的工作方式,但我建议您不要使用全局变量,尤其是方法。希望对您有帮助。
关于java - 为什么我的数组从方法中返回空白,但代码在主方法中运行时工作正常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60753137/