首页 > 解决方案 > 输入是程序应该打印的元素数量

问题描述

我想编写一个程序,打印一个整数序列,该序列写在一行中,数字以空格分隔。程序的输入是一个称为 n 的正整数,这是程序应该打印的序列中元素的数量。

例如,如果 n = 7,那么程序应该输出 1 2 2 3 3 3 4。

这是我的代码:

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n;
        n = scanner.nextInt();
        while (n == 0) {
            n = scanner.nextInt();
            for (int i = n; i <= n; i++) {
                System.out.println(i * n);
            }
        }
    }
}

是的,我不知道,这就是我寻求帮助的原因;)

标签: javaintegersequenceelement

解决方案


我不确定我是否理解你,但下面的代码

import java.io.IOException;
import java.util.Scanner;

public class Main {
    public static void main(final String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        int n;
        while ((n = scanner.nextInt()) > 0) {
            int count = 0;
            for (int i = 1; i < n && count < n; i++) {
                for (int j = 1; j <= i && count < n; j++) {
                    System.out.print(i + " ");
                    count++;
                }
            }
            System.out.println();
        }

    }
}

应该打印这个:

7
1 2 2 3 3 3 4
8
1 2 2 3 3 3 4 4

因为我假设您的示例中的行为:

例如,如果 n = 7,那么程序应该输出 1 2 2 3 3 3 4。

我相信这可以重写为更高效的代码(但对你来说更脏的代码)。


推荐阅读