java - 输入是程序应该打印的元素数量
问题描述
我想编写一个程序,打印一个整数序列,该序列写在一行中,数字以空格分隔。程序的输入是一个称为 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);
}
}
}
}
是的,我不知道,这就是我寻求帮助的原因;)
解决方案
我不确定我是否理解你,但下面的代码
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。
我相信这可以重写为更高效的代码(但对你来说更脏的代码)。
推荐阅读
- optimization - MariaDB - 大量请求时超时?该怎么办?
- model-view-controller - 从 _layout.cshtml 将参数传递给当前控制器
- android - 有时在 android studio 中未正确接收 Socket 数据
- reactjs - 如何在反应导航抽屉中添加多个分隔器组件
- swift - 如何触发在 .reality 文件中声明的实体动画
- python - sklearn 光学问题达到预期结果
- javascript - Joi 验证 - 不允许空对象
- php - Laravel 8 子文件夹内的控制器问题
- node.js - 如何修复节点中的“发送到客户端后无法设置标头”错误?
- javascript - 我的 javascript 代码中的错误代码“Uncaught TypeError: Cannot read property 'style' of null”