为什么使用for循环打印金字塔时会得到意想不到的输出?

huangapple 未分类评论52阅读模式
英文:

Why do I get unexpected output in printing a pyramid with for loops?

问题

如果在下面的sc.input中插入5

  *
 ***
*****

但是,我得到了下面的结果:

   *
 ***
*****

问题是什么?

public void test3() {
    Scanner sc = new Scanner(System.in);
    int n1 = sc.nextInt();
    for (int i = 0; i < n1; i++) {
        if (i <= n1 / 2) {
            for (int j = 0; j < n1; j++) {
                if (j < (n1 / 2) - i || j > (n1 / 2) + i) {
                    for (int m = 0; m < (n1 / 2) - i; m++) {
                        System.out.print(" ");
                    }

                } /*else if (j == 2) {

                    System.out.print("*");

                }*/ else {
                    System.out.print("*");

                }
            }
            System.out.println();
        }
    }
}
英文:

If 5 is inserted in sc.input below:

  *
 ***
*****

but, I got below:

   *
 ***
*****

What's the problem?

public void test3() {
	Scanner sc = new Scanner(System.in);
    int n1 = sc.nextInt();
    for(int i=0; i&lt;n1; i++){
        if(i&lt;=n1/2){
            for(int j=0; j&lt;n1; j++) {
                if( j&lt;(n1/2)-i || j&gt;(n1/2)+i ) {
                    for(int m=0; m&lt;(n1/2)-i; m++){
                        System.out.print(&quot; &quot;);
                    }
                    
                } /*else if( j==2 ) {
                    
                        System.out.print(&quot;*&quot;);
                    
                    
                }*/ else {
                    System.out.print(&quot;*&quot;);                       
                    
                }
            }
            System.out.println();
        }
    }
}

答案1

得分: 0

你的循环中存在一些逻辑错误:

for(int i=n1/2; i>=0; i--)  // (#1)
{
    for(int j=0; j<n1; j++) {
        if( j < i || j>n1-i-1 ) { // (#2) 
            System.out.print(" "); // (#3)
        } else {
            System.out.print("*");                       
        }
    }
    System.out.println();
}

我的备注(每个注释与代码部分中的特定部分对应,参见代码中的 (#numbers)):

  1. 为什么循环到 n1-1 并检查 n1/2?这样你会跳过一半的迭代,这是没有意义的。只需循环到 n1/2,这样你可以避免那个 if 条件。更好的做法是:让我们来数数,稍后会有用的。

  2. 我们需要一个全新的条件,以便理解何时需要打印空格。

    逻辑:在前几行(较大的 i 值)中,我们需要打印更多的空格。随着 i 的递减,我们将会有越来越少的空格(直到在最后一行中将没有空格)。你只需要构建一个范围:

    if( j < i || j > n1-i-1 )
    

    j > n1-i-1 中的最后一个 -1 是因为范围是从 0 到 n1-1

  3. 在我们找到正确的 j 条件以打印空格后,就没问题了。因此,我们不再需要使用 for 循环来打印空格。


请注意,这个逻辑对于偶数的 n1 值也适用。

n1=7 时的输出

   *   
  ***  
 ***** 
*******

n1=8 时的输出

   **
  ****
 ******
********
英文:

You had some logic errors in your loop:

for(int i=n1/2; i&gt;=0; i--)  // (#1)
{
    for(int j=0; j&lt;n1; j++) {
        if( j &lt; i || j&gt;n1-i-1 ) { // (#2) 
            System.out.print(&quot; &quot;); // (#3)
        } else {
            System.out.print(&quot;*&quot;);                       
        }
    }
    System.out.println();
}

My remarks (each note refers to a specific code part, see (#numbers) in code comments):

  1. Why looping up to n1-1 and checking for n1/2? In this way you skip half of your iterations, an that's pointless. Just loop up to n1/2 so that you can avoid that if-conditional.<br>Even better: let's count backyards; it will be useful later

  2. We need a brand you condition in order to understand when a space has to be printed.

    Logic: in the first rows (high i) we need to print more spaces. As i is decremented we will have less and less spaces (until, in the last row, we will have 0 of them). You just need to build a range:

     if( j &lt; i || j&gt;n1-i-1 )
    

    the last -1 in j&gt;n1-i-1 is required because the range is from 0 to n1-1

  3. After we found the correct condition on j for printing space, we are fine. So we don't need a forloop for printing spaces anymore


Please note how this logic works also for even values of n1.

Output for n1=7:

   *   
  ***  
 ***** 
*******

Output for n1=8:


   **
  ****
 ******
********

答案2

得分: 0

我注意到每行打印出现的星号数量是奇数。用户的输入是收集要打印的行数,还是收集最后一行中的星号最大数量?如果输入是收集要打印到屏幕上的行数,则可以像下面的代码所示进行操作。

import java.util.Scanner;

/**
 * 输出:
 *
 * 输入行数:10
 *              *
 *             ***
 *            *****
 *           *******
 *          *********
 *         ***********
 *        *************
 *       ***************
 *      *****************
 *     *******************
 *
 * 作者:martinfall
 */
public class Test {

    /**
     * 主方法。
     *
     * @param args
     */
    public static void main(String[] args) {
        // 创建一个新的 Scanner 对象
        Scanner input = new Scanner(System.in);

        // 提示用户输入行数
        System.out.print("输入行数:");
        int number = input.nextInt(); // number 存储行数

        // 外循环打印用户输入的行数
        for (int i = 0; i < number; i++) {
            // 用必要的空格填充每行
            for (int j = 0; j < Math.ceil(number - i); j++) {
                System.out.print(" ");
            }

            // 每行打印奇数数量的星号,如 1、3、5 等
            for (int k = 0; k < (2 * i) + 1; k++) {
                System.out.print("*");
            }

            // 在每行末尾打印换行符
            System.out.println();
        }
    }
}

如果输入是收集最后一行中的星号数量,则在平衡奇数/偶数行的星号上会有一些难度。

英文:

I noticed that each line printed has an odd number of *. Is the user input to collect the number of lines, or is it to collect the maximum number of * in the last line? If the input collect the number of lines to print to the screen, then you can do it as shown in the code below.

import java.util.Scanner;

/**
 * Output:
 *
 * Enter the number of rows: 10
 *              *
 *             ***
 *            *****
 *           *******
 *          *********
 *         ***********
 *        *************
 *       ***************
 *      *****************
 *     *******************
 *
 *
 * @author martinfall
 */
public class Test {

    /**
     * Main method.
     *
     * @param args
     */
    public static void main(String[] args) {
        // Create a new Scanner object
    Scanner input = new Scanner(System.in);

    // Prompt the user to enter the number of row 
    System.out.print(&quot;Enter the number of rows: &quot;);
    int number = input.nextInt(); // number holds the number of rows

    // Outer loop prints the number of lines entered by user
    for (int i = 0; i &lt; number; i++) {
        // Pad each line with the necessary blank spaces
        for (int j = 0; j &lt; Math.ceil(number - i); j++) {
            System.out.print(&quot; &quot;);
        }

        // Print an odd number of * on each line, such as 1, 3, 5, etc.
        for (int k = 0; k &lt; (2 * i) + 1; k++) {
            System.out.print(&quot;*&quot;);
        }

        // Print a new line at the end of each line of *
        System.out.println();
        }
    }
}

If the input is to collect the number of * in the last line, then it gets a little tricky to balance the odd/even lines of *

huangapple
  • 本文由 发表于 2020年7月27日 16:08:01
  • 转载请务必保留本文链接:https://java.coder-hub.com/63111146.html
匿名

发表评论

匿名网友

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

确定