我必须使用一维数组来创建一个盒子。请记住,我不允许使用2D数组。
到目前为止,这是我的代码:String input = "";
int N = InputNumber(input);
char [] Board = new char[N];
int M = (int) Math.sqrt(N);
System.out.println("Printing " + (M) + " x " + (M) + " board...");
char A = 'O';
for(int i = 0; i < Math.sqrt(Board.length); i++)
{
Board[i] = A;
System.out.println(Board[i]);
}
用户选择一个数字,之后程序会创建一个框。 所以例如如果N = 4,程序应该创建一个16元素数组,打印方式如下:
OOOO
OOOO
OOOO
OOOO
这个盒子将被视为x和y坐标,并且将添加其他方法,其中用户输入x和y坐标,O将切换到X.我只是不太确定如何拆分阵列这样它就可以根据需要打印出来。我的程序只是迭代数组的元素并将它们打印出来......
答案 0 :(得分:0)
我相信你在找这样的东西?
int n = 4; //change this back to what you had for user input and stuff
char [] board = new char[n*n];
Arrays.fill(board, 'O');
int m = (int) Math.sqrt(n); //no idea why you need this?
System.out.println("Printing " + (n) + " x " + (n) + " board...");
for(int i = 0; i < board.length; i++)
{
if((i%n) == 0)
System.out.println();
System.out.print(board[i]);
}
输出:
Printing 4 x 4 board...
OOOO
OOOO
OOOO
OOOO
答案 1 :(得分:0)
你必须创建n * n数组ex: - 如果用户输入4,那么数组应该是4 * 4 = 16个元素
int N = InputNumber(input);
char A = 'O';
char [] board = new char[N*N];
int m = (int) Math.sqrt(N); //i don't know why you need this
System.out.println("Printing " + N + " x " + N + " board...");
for(int i = 0; i < board.length; i++)
{
board[i] = A;
if((i%N) == 0){
System.out.println();
}
System.out.print(board[i]);
}
答案 2 :(得分:0)
让1D数组只包含您的值,现在使用坐标指向特定值此方法效果很好:
// Using 0-index based representation.
// if user entered (1,3) i.e. 0th row and 3rd element(2nd index element)
public int getPosition(int x,int y,int N)
{
int val1 = (x-1) * N;
int val2 = y;
int targetIndex = val1 + val2; // this will point to 3rd value (index will be 2) in array
return (targetIndex -1 );
}
上述方法将返回1D数组中的(x,y)索引。所以,您刚刚使用一维数组作为N * N的框。