如何解决输入是程序应打印的元素数
我想编写一个程序,该程序打印用单行写成的整数序列,数字之间用空格分隔。程序的输入是一个称为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。
我相信可以将其重写为更有效的代码(但对您而言更脏的代码)。
,这是一种发表评论的方式
n = scanner.nextInt();
int viewNumber = 1;// for printing number
while (n > 0) { // if any number printing left
for (int i = 1; i <= viewNumber; i++) { // This loop print viewNumber viewNumber's times
System.out.print(viewNumber + " ");
n--; // decrease n value after printing a number
if(n == 0) { // break the loop if print n numbers already
break;
}
}
viewNumber++; // increase view number after showing it's that times
}
,
尝试一下,我使用了2个循环
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter any digit");
int n;
n = scanner.nextInt();
for(int a = 0;n>=a;a++) {
for (int i = 0; a > i; i++) {
System.out.print(" "+a);
}
}
}
输入:5 输出:1 2 2 3 3 3 4 4 4 4 5 5 5 5 5
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。