java - For 循环星号和加号(矩形形式)

标签 java loops for-loop ascii-art

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

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
****                            ****
****                            ++++
****                            ****
****                            ++++
****                            ****

最佳答案

只需在 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();
    }
}

关于java - For 循环星号和加号(矩形形式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32743455/

相关文章:

java - 如何在 Spring 服务的 @Transactional 方法中实现 Oracle ADF ApplicationModule 和 JPA 之间的共享事务?

java - Maven 依赖项仅下载 pom 而不是新版本的 jar

loops - Ada - 除一个 float 并循环它直到它达到零

c++ - 固定更新速度

javascript - 我想隐藏特定单元格的表格行

python - 为每个循环 append 到新列表

c - for 循环中的相等性测试

java - 通过具有可变数量参数的反射调用方法

java - 如何使用 Java native 接口(interface)从 Java 调用 Go 函数?

javascript - React - 使用循环创建嵌套组件