Java循环数模式

Java循环数模式,java,for-loop,Java,For Loop,如何执行for循环语句,使输出类似于(ii)01 12 2 3 3 3 4 4?我似乎无法得到输出的正确答案 for(int i = 0; i <= 4; i++) { for(int j = 0; j < i; j++) { System.out.print(j + " "); } } for(inti=0;i当您现在获得代码时,以下是您的错误: for(int i = 0; i<=4; i++){ // You´re printin

如何执行for循环语句,使输出类似于(ii)01 12 2 3 3 3 4 4?我似乎无法得到输出的正确答案

for(int i = 0; i <= 4; i++) {
    for(int j = 0; j < i; j++) {
        System.out.print(j + " ");
    }
}

for(inti=0;i当您现在获得代码时,以下是您的错误:

for(int i = 0; i<=4; i++){
    // You´re printing 0 once, so in order to loop you have to loop until j<=i
    for(int j = 0; j<=i; j++){
        // You actually did want to print i here, as it will increment.
        // like 0, 1, 2, 3, 4. in Order to achive your pattern.
        // When printing j it will allways start with 0 again, as it´s the nested loop
        System.out.print(i + " ");
    }
}

要为输出写入for循环语句
0 1 1 2 2 3 3 3 3 4 4 4
,您需要使用OEIS中的序列:

for(int i = 0; i < 15; ++i) {
    System.out.print(((int) Math.floor((1 + Math.sqrt(1 + 8 * i)) / 2) - 1) + " ");
}
for(int i=0;i<15;++i){
System.out.print(((int)Math.floor((1+Math.sqrt(1+8*i))/2)-1+“”);
}

你可以测试它。

一个小小的提示,两个嵌套的循环就可以了:),尽管这不是一个问题,因为它基本上是一个代码请求计数,每个数字
n
打印
n+1
次。一点也不难。好吧……那你是怎么意识到你没有正确的答案的呢?我试着做嵌套循环,但似乎我仍然没有得到它的公共类hello{public static void main(String[]args){for(int i=0;ii得到了正确答案。您的代码有一个小错误。请将您的运算符从j=@ASHWIIN改为whups my bad)
for(int i = 0; i < 15; ++i) {
    System.out.print(((int) Math.floor((1 + Math.sqrt(1 + 8 * i)) / 2) - 1) + " ");
}