【问题标题】:Create a number pyramid that decreases in value but each iteration goes up by odd numbers创建一个数值递减但每次迭代增加奇数的数字金字塔
【发布时间】:2021-10-22 20:28:45
【问题描述】:

我们的任务是创建一个数字金字塔,随着它的下降,它的值会降低,但每次迭代都会以奇数重复它。我试图瞄准的输出是:

    5
   444
  33333
 2222222
111111111

但它不会打印完整的金字塔,只会打印从 5 到 3 的数字。

这是我使用的代码:

import java.util.Scanner;

public class LoopExercise2 {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        
        int rows = 5;
        
        // row counter; total rows will be decided by the scanned input
        for (int counter = 1; counter <= rows ; ++counter) {
            //System.out.print("7");
            // space counter before the number; creates the pyramid effect
            for (int space = 0; space <= rows ; ++space ) {
                System.out.print(" ");
            }
            
            // per iteration, prints an odd number of values
            int n_counter = 0; // Initialize value to 0
            while (n_counter != 2 * counter - 1) {
                System.out.print(rows);
                ++n_counter;
            }
            // deducts 1 from the scanned input
            rows--;
            // prints a space to break the line
            System.out.println();
        }
    }
}

【问题讨论】:

  • 那么你的问题是什么?
  • 对不起,我忘了添加它,基本上输出直到 1s 才达到……它只打印出 5 到 3 位,不像它应该做的那样
  • 您了解过在 Eclipse 中使用调试器吗?现在是了解它的好时机。在循环上设置断点并调试
  • 我也是 Eclipse 新手,但我会努力学习,谢谢

标签: java loops


【解决方案1】:

试试这个。

public static void main(String[] args) {
    int rows = 5;
    for (int i = rows, j = 1; i > 0; --i, j += 2)
        System.out.println(" ".repeat(i) + Integer.toString(i).repeat(j));
}

输出:

     5
    444
   33333
  2222222
 111111111

【讨论】:

  • 这对我来说是新的,谢谢你的回答我现在试着理解它
【解决方案2】:

您的循环停止条件每次都在变化。 counter &lt;= rows++counterrows-- 一样

因此,循环停止在initial rows value / 2

我建议您对打印和递减的数字使用单独的变量

【讨论】:

  • 但是改变变量不会改变整个输出?因为这些行也决定了要减 1 的数字?
  • 没有?添加一个仅用于打印的变量不会改变您的循环从counter = 1; counter &lt;= 5.. 我说您的问题是您当前正在修改 5 以使其更小,同时计数器变大.您应该删除 row-- 并让循环实际转到 5,但您需要在每一行打印一个不同的变量
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-17
  • 1970-01-01
  • 1970-01-01
  • 2021-08-20
相关资源
最近更新 更多