我目前正在尝试制作一个形状有点麻烦我的代码是:
winsound.PlaySound(G5.wav)
一切正常,除了我的上一个方法“fancySquare”没有打印出我想要的方式。如果用户输入为9:
,它当前正在打印此形状winsound
它应该是这样的
import java.util.Scanner;
public class Problem2
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int n = 0;
do
{
System.out.print("Enter an odd integer greater than or equal to 5: ");
n = input.nextInt();
}while(n < 5 || n % 2 == 0);
boxWithMinorDiagonal(n);
rightTriangle(n);
printNLetter(n);
fancySquare(n);
}
public static void fancySquare(int n)
{
System.out.println();
int tempRow = 2;
int tempCol = 2;
int tempColDec = n - 2;
int tempRowInc = 2;
for(int row = 1; row <= n; row++)
{
for(int col = 1; col <= n; col++)
{
if(row == 1 || row == n || col == 1 || col == n)
{
if(row == 1 && col == 1 || row == 1 && col == n || row == n && col == 1 || row == n && col == n)
{
System.out.print("@");
}
else
{
System.out.print("*");
}
}
else if(tempRow == row && tempCol == col)
{
System.out.print("+");
tempCol++;
tempRow++;
}
else
{
System.out.print(" ");
}
if(row == tempRowInc && col == tempColDec)
{
System.out.print("+");
tempColDec--;
tempRowInc++;
}
}
System.out.println();
}
}
}
答案 0 :(得分:0)
尝试使用命名布尔值进行检查,以使其更容易理解。 更常见的是使用零基索引,但我坚持你的版本,使它更相似,更容易匹配。
public static void fancySquare(int n) {
System.out.println();
for (int row = 1; row <= n; row++) {
for (int col = 1; col <= n; col++) {
final boolean firstRow = row == 1;
final boolean lastRow = row == n;
final boolean firstCol = col == 1;
final boolean lastCol = col == n;
// calc the center
final boolean center = row == (n + 1) / 2 && col == (n + 1) / 2;
// calc the marker
final boolean marker = row == col || n - row + 1 == col;
// we need the @ marker at the corners (1,1) || (1,n) || (n,1) || (n,n)
if ((firstRow || lastRow) && (firstCol || lastCol)) {
System.out.print("@");
// we need the * in the first & last column/row which is no corner
} else if (firstRow || lastRow || firstCol || lastCol) {
System.out.print("*");
// we need a @ also in the center
} else if (center) {
System.out.print("@");
// we need the plus on the diagonals
} else if (marker) {
System.out.print("+");
// instead we need a space
} else {
System.out.print(" ");
}
}
System.out.println();
}
}