我正在用Java创建一个文本游戏,它使用2D数组作为电路板。我想这样做,当我输入“扫描”命令时,它每次都会打印相同的8x8板。程序编译得很好我只需要知道如何打印每次运行“scan”命令时生成的相同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
答案 0 :(得分:1)
如果这是一个简单的程序,您可以进行简单的更改来执行此操作。只需将数组的范围扩展到类级别,然后创建扫描方法。
public class Main {
static Scanner in = new Scanner(System.in);
String[][] board;
...//Your other code
public static scan() {
//Printing/Drawing logic
}
}
然后你可以为&#34; scan&#34;添加一个select语句。到你当前的输入检查,这将运行该方法。
然而,当涉及到这样的设计时,我宁愿有一些由2D数组支持的Board
类,它可以包含许多有用的程序函数,包括Board.scan()
,以及甚至可能是帮助类来解析输入字符串。