gpt4 book ai didi

java - 如何在java中一行打印字符串 block

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

我是java新手,我发现一个 Activity 需要您根据循环计数打印字符串 block 。输入应该是:

 Input Format:
2
1
3

输出必须是:

    *     *
** **
*** ***
**** ****
***** *****

*
**
***
****
*****

* * *
** ** **
*** *** ***
**** **** ****
***** ***** *****

我很难做到这一点,因为我无法将其打印在一行中。这是我的代码:

import java.util.Scanner;
public class Main
{
public static void main (String[]args)
{
Scanner sc = new Scanner (System.in);
int num1, num2, num3;
num1 = Integer.parseInt (sc.nextLine ());
num2 = Integer.parseInt (sc.nextLine ());
num3 = Integer.parseInt (sc.nextLine ());

String barricade = " *\n"
+ " **\n"
+ " ***\n"
+ " ****\n"
+ " *****\r";

for (int i = 0; i < num1; i++)
{
System.out.print(barricade);
}
}
}

最佳答案

这是一个工作脚本:

Scanner sc = new Scanner (System.in);
String[] lines = {" *", " **", " ***", " ****", " *****"};
int input = Integer.parseInt(sc.nextLine());
for (int i=0; i < lines.length; ++i) {
for (int j=0; j < input; ++j) {
System.out.print(lines[i]);
System.out.print(" ");
}
System.out.println();
}

我们可以在这里使用嵌套循环,其中外循环迭代三角形的线,内循环控制每行打印多少个三角形。对于输入 3,生成:

      *       *       *
** ** **
*** *** ***
**** **** ****
***** ***** *****

关于java - 如何在java中一行打印字符串 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58600571/

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