gpt4 book ai didi

语句的 Java 代码格式

转载 作者:行者123 更新时间:2023-11-29 05:14:42 25 4
gpt4 key购买 nike

他们是格式化此 for-loop 的更好方法吗?

用户输入两个初始化为x 和y 的整数,程序打印出这些值,第一个数字为+,第二个数字为-。

FOR EXAMPLE 9 and 5 would result in

+++++++++-----

我尝试使用嵌套的for-loop,但这导致了

+-----+-----+-----+-----+-----+-----+-----+-----+-----

    Scanner sc = new Scanner(System.in);
int x,y,total = 0;

System.out.println("Enter two numbers greater than 0 and no greater than 20!");
x = sc.nextInt();
y = sc.nextInt();

draw(x,y);

private static void draw(int x, int y) {
for(int i=1; i<=x; i++)
{
System.out.print("+");

}
for(int j=1; j<=y; j++)
{
System.out.print("-");
}
}

最佳答案

如果你想让它变小:)

private static void draw(int x, int y) {
for (int i = -x; i < y; i++) {
System.out.print(i<0 ? "+" : "-");
}
}

关于语句的 Java 代码格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27002032/

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