对角星星挑战,不理解它的概念?

huangapple go评论97阅读模式
英文:

Diagonal Star Challenge, not understanding it's concept?

问题

以下是一个对角星星挑战的解决方案,基本上根据分配给定参数的值打印出星星。现在我理解嵌套循环的工作原理,i 会与 j 的索引进行比较,但我不明白的是,为什么在只有一个 if 语句的情况下,它是如何在每一行打印出星星的呢?如果循环满足了其中一个条件,难道不应该在每一行只打印一个星星吗?为什么仅仅一个 if 语句就能创建出这么多不同的图案呢?

  1. public static void printSquareStar(int number) {
  2. if (number < 5) {
  3. System.out.println("无效的值");
  4. } else {
  5. for (int i = 0; i < number; i++) {
  6. for (int j = 0; j < number; j++) {
  7. if (i == 0 || j == 0 || i == j || i == (number - 1) ||
  8. j == number - 1 || i + j == (number - 1)) {
  9. System.out.print("*");
  10. }
  11. // 如果以上条件都不满足,则在该列上留一个空格
  12. else {
  13. System.out.print(" ");
  14. }
  15. }
  16. // 创建新的一行
  17. System.out.println();
  18. }
  19. }
  20. }

输出结果:

  1. *****
  2. ** **
  3. * * *
  4. ** **
  5. *****
英文:

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?

  1. public static void printSquareStar(int number) {
  2. if (number &lt; 5) {
  3. System.out.println(&quot;Invalid Value&quot;);
  4. } else {
  5. for (int i = 0; i &lt; number; i++) {
  6. for (int j = 0; j &lt; number; j++) {
  7. if (i == 0 || j == 0 || i == j || i == (number - 1) ||
  8. j == number - 1 || i + j == (number - 1)) {
  9. System.out.print(&quot;*&quot;);
  10. }
  11. //none of these operations work then just leave a space
  12. //on that column
  13. else {
  14. System.out.print(&quot; &quot;);
  15. }
  16. }
  17. //creates a new row
  18. System.out.println();
  19. }
  20. }
  21. }

output:

  1. *****
  2. ** **
  3. * * *
  4. ** **
  5. *****

答案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.

huangapple
  • 本文由 发表于 2020年9月24日 05:58:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/64036847.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定