【问题标题】:For loop asterisk and plus sign (Rectangle form)For 循环星号和加号(矩形形式)
【发布时间】:2015-09-23 15:18:23
【问题描述】:

我想制作一个程序,用户输入矩形的高度和宽度,但交替使用*+。这是我的代码:

class Parallelogram {
    public static void main(String[] args) {
        Scanner x = new Scanner(System.in);
        int w;
        int h;

        System.out.print("Enter the Width ");
        w = x.nextInt();
        System.out.print("Enter the height ");
        h = x.nextInt();

        for (int i = 0; i < h; i++) {
            for (int j = 0; j < w; j++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

输出:

MY PROGRAM :                   What i want my program to look
Enter width : 4                 Enter width : 4
Enter height : 5                Enter height : 5
****                            ****
****                            ++++
****                            ****
****                            ++++
****                            ****

【问题讨论】:

  • 你可以使用if (i%2 == 0) print asterix else print plus

标签: java loops for-loop ascii-art


【解决方案1】:

只需在你的 for 循环中添加一个模数。

此代码将为您解决问题:

public static void main(String[] args) {
    Scanner x = new Scanner(System.in);
    int w;
    int h;
    System.out.print("Enter the Width ");
    w = x.nextInt();
    System.out.print("Enter the height ");
    h = x.nextInt();
    for (int i = 0; i < h; i++) {
        for (int j = 0; j < w; j++) {
            if (i % 2 == 0) {
                System.out.print("*");
            } else {
                System.out.print("+");
            }
        }
        System.out.println();
    }
}

【讨论】:

    猜你喜欢
    • 2016-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多