我正在嘗試制作一個瓷磚圖案生成器方法。我不確定如何執行 for 回圈,以便一旦 x 字符在中心相遇,它們就會轉到對角線。
到目前為止我的代碼是:
public static void crosses(int x, int y, char g, char filler,boolean p) {
if(p== false) {
int temp = 0;
for(int i=0;i<y;i ) {
for(int j=0;j<x;j ) {
if(j == 2 i||j==8-i)
output[i][j] = "x";
else
output[i][j] = ".";
}
}
for(int i=0;i<length;i ) {
for(int j=0;j<height;j ) {
System.out.print(output[i][j]);
}
System.out.println();
}
}
}
g.crosses(12, 12, 'x', '.', false); 應該輸出
..x......x..
...x....x...
x...x..x...x
.x...xx...x.
..x..xx..x..
...xx..xx...
...xx..xx...
..x..xx..x..
.x...xx...x.
x...x..x...x
...x....x...
..x......x..
我嘗試使用臨時變數來增加但沒有解決上述問題
uj5u.com熱心網友回復:
public static void crosses(int height, int length, char main, char filler, boolean pattern) {
char[][] output = new char[height][length];
if(pattern == false) {
for(int i = 0; i<length; i ) {
for (int j = 0; j < height; j ) {
if (j == (i - 2) || j == (i 2) || j == (height - i - 3) || j == (height - i 1)) {
output[i][j] = main;
}
else {
output[i][j] = filler;
}
}
}
}
for (char[] row : output) {
for (char c : row) {
System.out.print(c);
}
System.out.println();
}
}
上面的代碼盡可能接近你的代碼,但這里有一些對你撰寫它的方式的改進:
public static char[][] crosses(int height, int length, char main, char filler, boolean pattern) {
char[][] output = new char[height][length];
if (pattern) {
for (char[] row : output) { Arrays.fill(row, filler); }
return output; // I made an assumption that if true, the output should be filled with filler only.
}
// no need to do pattern == false, just leave using return if true.
for(int i = 0; i<length; i ) {
for (int j = 0; j < height; j ) {
if (j == (i - 2) || j == (i 2) || j == (height - i - 3) || j == (height - i 1)) {
output[i][j] = main;
}
else {
output[i][j] = filler;
}
}
}
return output; // Better to delegate the print to the caller, so they can decide how to print it.
}
public static void main(String[] args) {
char[][] result = crosses(12, 12, 'x', '.', false);
for (char[] row : result) {
System.out.println(row); // better than another for loop as it's already built in.
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/536577.html
標籤:爪哇for循环
