嵌套循环模式

时间:2017-09-25 10:58:48

标签: java loops nested

所以是的,我现在正在研究嵌套循环,但我认为我被困在某处,因为我想要的输出是:

*
**
***
**
*

这是我的代码:

    //intro here
    int x = 0;
        System.out.print("Enter: ");
        x = var.nextInt();
        for(int a = 1; a <= x; a++){
            for(int b = 0; b <= x - a; b++){
                System.out.print("");
            }
            for(int c = 0; c < a; c++){
                System.out.print("*");
            }
        System.out.println();
        }
    }
}

但输出的结果是:

*
**
***

我现在不知道该怎么做,是否还需要ford--的其他$http

2 个答案:

答案 0 :(得分:1)

是。你需要另一个for循环来打印减少数量的星星。这应该运作良好!

import java.util.Scanner;

public class Nested {
    public static void main(String[] args) {
        Scanner var = new Scanner(System.in);
        int x = 0;
        System.out.print("Enter: ");
        x = var.nextInt();

        //create star rows from 1 to 6
        for (int a = 1; a <= x; a++) {
            for (int b = 1; b <= a; b++) {
                System.out.print("*");
            }
            System.out.println();
        }

        //create start rows from 5 to 1
        for (int a = x - 1; a > 0; a--) {
            for (int b = a; b > 0; b--) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

答案 1 :(得分:0)

    int x = 0;
    System.out.print("Enter: ");
    x = var.nextInt();
    for(int a = 1; a <= x; a++){
        for(int b = 0; b <= x - a; b++){
            System.out.print("");     //this code block do nothing in ur case
        }
        for(int c = 0; c < a; c++){
            System.out.print("*");
        }
    System.out.println();
    }
}

您可以通过以下方式获得所需的输出:

    int x = 0;
    System.out.print("Enter: ");
    x = var.nextInt();
    for(int a = 1; a <= x; a++){
        for(int c = 0; c < a; c++){
            System.out.print("*");
        }
        System.out.println();
    }
    for (int a = x - 1; a > 0; a--){
        for(int c = a; c > 0; c--)
            System.out.print("*");
         System.out.print(""\n");
    }