英文:
Diagonal Star Challenge, not understanding it's concept?
问题
以下是一个对角星星挑战的解决方案,基本上根据分配给定参数的值打印出星星。现在我理解嵌套循环的工作原理,i
会与 j
的索引进行比较,但我不明白的是,为什么在只有一个 if 语句的情况下,它是如何在每一行打印出星星的呢?如果循环满足了其中一个条件,难道不应该在每一行只打印一个星星吗?为什么仅仅一个 if 语句就能创建出这么多不同的图案呢?
public static void printSquareStar(int number) {
if (number < 5) {
System.out.println("无效的值");
} else {
for (int i = 0; i < number; i++) {
for (int j = 0; j < number; j++) {
if (i == 0 || j == 0 || i == j || i == (number - 1) ||
j == number - 1 || i + j == (number - 1)) {
System.out.print("*");
}
// 如果以上条件都不满足,则在该列上留一个空格
else {
System.out.print(" ");
}
}
// 创建新的一行
System.out.println();
}
}
}
输出结果:
*****
** **
* * *
** **
*****
英文:
So below is a solution of a diagonal star challenge, which basically prints out stars based on the value assigned to the given parameter. Now I understand how nested loops functions, i
will be compared with the index of j
, but what I don't understand is, how is it printing out stars in a each row when there is only 1 if statement? If the loop meets one of it's conditions should it not just print out 1 star on each row? Why is it creating so many different patterns from just a single if statement?
public static void printSquareStar(int number) {
if (number < 5) {
System.out.println("Invalid Value");
} else {
for (int i = 0; i < number; i++) {
for (int j = 0; j < number; j++) {
if (i == 0 || j == 0 || i == j || i == (number - 1) ||
j == number - 1 || i + j == (number - 1)) {
System.out.print("*");
}
//none of these operations work then just leave a space
//on that column
else {
System.out.print(" ");
}
}
//creates a new row
System.out.println();
}
}
}
output:
*****
** **
* * *
** **
*****
答案1
得分: 3
在你的If语句中,它会打印一个 * 如果 i 或 j 符合条件。|| 是或的意思,所以它的意思是如果 (i == 0 或 j == 0 或 i == j 或 i == (number - 1)
或 j == number - 1 或 i + j == (number - 1)) 那么打印一个 *,但如果 i 或 j 不符合条件,就打印一个空格。你可以为每种其他情况都使用 if else,这样会更容易阅读。
英文:
In your If statement it prints a * I or j fits the criteria. the || is or, so it is saying if (i == 0 or j == 0 OR i == j OR i == (number - 1)
OR j == number - 1 OR i + j == (number - 1)) then print a *, but if I or j doesn't not fit that print a space. You could have an if else for every other case which would make it easier to read.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论