我正在用 Java 创建一个文本游戏,它使用 2D 数组作为棋盘。我想这样做,这样当我输入“扫描”命令时,它每次都会打印相同的 8x8 板。程序编译得很好,我只需要知道如何打印每次运行“扫描”命令时生成的相同 8x8 板。
import java.util.*;
import java.math.*;
import java.util.Random;
import java.util.Scanner;
import java.text.*;
import java.io.*;
public class Main {
static Scanner in = new Scanner(System.in);
public static void Start() {
System.out.println("Would you like a Short, Medium, or Long game?");
String x = in.nextLine();
System.out.println("Are you a Novice, Fair, Good, Expert, or Emeritus player?");
String y = in.nextLine();
System.out.println("Good Luck!");
System.out.println("What would you like to do?");
}
public static void main() {
//create the grid
String x;
String y;
String z;
z = in.nextLine();
if (z.equals("scan")) {
final int rowWidth = 8;
final int colHeight = 8;
Random rand = new Random();
boolean a = true;
boolean b = true;
boolean c = true;
boolean d = true;
String [][] board = new String[rowWidth][colHeight];
//fill the grid
for (char row = 0; row < board.length; row++) {
for (char col = 0; col < board[row].length; col++) {
double r = Math.random();
if(a == true && r <= .02) {
board[row][col] = "P";
a = false; }
else if(b == true && r <= .04 && r > .02){
board[row][col] = "K";
b = false; }
else if(c == true && r <= .06 && r > .04){
board[row][col] = "B";
c = false; }
else if(d == true && r <= .08 && r > .06){
board[row][col] = " ";
d = false; }
else
board[row][col] = "*";
}
}
//display output
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[i].length; j++) {
System.out.print(board[i][j] + " ");
//System.out.println();
}
System.out.println();
}
System.out.println("");
z = in.nextLine();
main();
}else if( z.equals("exit")) {
System.exit(0);
}else {
System.out.println("Parton");
main();
}
}
public static void run() {
Start();
main();
}
}//end of main
//end of class Main
最佳答案
如果这是一个简单的程序,您可以进行简单的更改来执行此操作。只需将数组的范围扩大到类级别,然后创建一个扫描方法即可。
public class Main {
static Scanner in = new Scanner(System.in);
String[][] board;
...//Your other code
public static scan() {
//Printing/Drawing logic
}
}
然后您只需将“扫描”的选择语句添加到当前的输入检查中即可运行该方法。
但是,当涉及到这样的设计时,我更喜欢有某种由 2D 数组支持的 Board
类,它可以包含许多对程序有用的函数,包括 Board .scan()
,甚至可能还有一个用于解析输入字符串的辅助类。
关于java - 存储二维数组并稍后在 Java 中再次调用它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36695918/