gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:21:19 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com