我在打印代码时遇到问题。我需要使用用户输入大小的网格来打印棋盘。
它应输出的示例。
Input a size (must be larger than 1):
5
0 * * *
1 * *
2 * * *
3 * *
4 * * *
这是我的代码:
import java.util.Scanner;
public class nestedpractice1
{
public static void main(String[] args)
{
Scanner kbinput = new Scanner(System.in);
//Create Size variable
System.out.println("Input a size: ");
int n = 0; n = kbinput.nextInt();
for(int r = 0; r < n; r++)
{
for(int c = 0; c < r; c++)
{
if((r%2) == 0)
{
System.out.print("*");
}
else if((r%1) == 0)
{
System.out.print(" *");
}
}
System.out.println("");
kbinput.close();
}
}
}
我的代码不断打印
**
****
最佳答案
该循环精确地产生您指定的输出:
for (int r = 0; r < n; r++) {
System.out.print(r);
for (int c = 0; c < n; c++) {
System.out.print(r % 2 == 1 ^ c % 2 == 0 ? " *" : " ");
}
System.out.println();
}
我将内部循环的主体压缩为单个
print
语句。该语句使用^
(异或)运算符测试条件,然后使用?:
(三进制)运算符(如果条件为true
则打印星号,或者如果条件为false
则空格)。我们可以分解单个语句,同时保留其含义,如下所示:
boolean isOddRow = r % 2 == 1;
boolean isEvenCol = c % 2 == 0;
System.out.print(isOddRow ^ isEvenCol ? " *" : " ");
作为解释,我们仅在行和列均为偶数或均为奇数时才打印
*
。因此,如果行是偶数但列为奇数,或者如果行是奇数但列是偶数,则仅打印空格。我们可以通过以下方式使用
==
代替^
表示相同的逻辑: boolean isEvenRow = r % 2 == 0;
boolean isEvenCol = c % 2 == 0;
System.out.print(isEvenRow == isEvenCol ? " *" : " ");
或者,如果您更喜欢速记
if..else
而不是速记三元运算符: if (isEvenRow == isEvenCol) {
System.out.print(" *");
} else {
System.out.print(" ");
}