为什么此程序会打印以下输出?
import java.util.Arrays;
import java.util.Collections;
public class FifteenModel implements Boardgame
{
private String currentMessage = "No message yet";
private String[][] status = new String[4][4]; // spelplanen
private int iemp, jemp;
public void FiftenModel()
{
createGameBoard();
}
private void createGameBoard()
{
String[] rutor = new String[16]; //Skapar matrisen
for (int i = 1; i <= 16; i++)
{
rutor[i-1] = String.valueOf(i);
if (i == 16)
{
rutor[i-1] = null;
}
}
shuffleGameBoard(rutor);
}
private void shuffleGameBoard(String[] rutor)
{
Collections.shuffle(Arrays.asList(rutor));
saveArray(rutor);
}
private void saveArray(String[] rutor)
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
status[i][j] = rutor[4 * i + j ];
if (status[i][j] == null)
{
status[i][j] = "";
iemp = i;
jemp = j;
}
}
}
}
public boolean move(int i, int j)
{
if (((iemp - 1 <= i) && (i <= iemp + 1)) && ((jemp - 1 <= j) && (j <= jemp + 1)))
if ((iemp == i) ^ (jemp == j))
{
currentMessage = "Elements is changed!";
status[iemp][jemp] = status[i][j];
status[i][j] = "";
iemp = i;
jemp = j;
return true;
}
currentMessage = "Choose the right element!";
return false;
}
public String getStatus(int i, int j){
return status[i][j];
}
public String getMessage(){
return currentMessage;
}
public boolean gameDone(){
for (int j = 0; j < 4; j++)
for (int i = 0; i < 4; i++)
try {
if (Integer.valueOf(getStatus(i,j)) == (j * 4 + i + 1))
{
currentMessage = "Congrats!";
return true;
}
} catch (Exception e){
}
return false;
}
}
使用此输出:
Welcome to fifteen puzzle
null null null null
null null null null
null null null null
null null null null
Your move:
为什么它为空?它假设为1到15,最后一个为null,然后程序假定将该矩阵洗牌。现在,我认为问题在于shuffle方法,但由于我是初学者,因此我很难找到它。
!编辑!另一个文件。
class Text15 {
public static void main(String[] u) {
Scanner scan = new Scanner(System.in);
Boardgame thegame = new FifteenModel(); // Model object is created
System.out.println("\nWelcome to fifteen puzzle\n");
while (true) {
// Print the current board
for (int i=0; i<4; i++) {
for (int j=0; j<4; j++)
System.out.print(" " + thegame.getStatus(i,j)); // getStatus
System.out.println();
}
System.out.println();
System.out.print("Your move: ");
int i = scan.nextInt(); // get an int number from terminal window
int j = scan.nextInt();
thegame.move(i,j); // move
System.out.println(thegame.getMessage()); // getMessage
}
}
}
答案 0 :(得分:2)
您已创建名为FiftenModel
但你想要的是构造函数
public FifteenModel () // fix spelling mistake as well
{
createGameBoard();
}
同时尝试调试代码以确定status[i][j] = rutor[4 * i + j ];
是否正确,因为它看起来会超出范围异常