简体   繁体   English

如何在 java 的一行中打印一个字符串块

[英]How do i print a block of strings in one line in java

I'm new to java and i found an activity that needs you to print a block of strings based on a count of a loop.我是 java 的新手,我发现一个活动需要您根据循环计数打印一个字符串块。 The input should be:输入应该是:

 Input Format:
     2
     1
     3

And the output must be:并且 output 必须是:

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

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

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

I'm having a hard time doing this because i can't print it in one line.我很难做到这一点,因为我无法将它打印在一行中。 Here's my code:这是我的代码:

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);
    }
  }
}

Here is a working script:这是一个工作脚本:

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

We can use a nested loop here, where the outer loop iterates over the lines of the triangle, and the inner loop controls how many triangles get printed on each line.我们可以在这里使用嵌套循环,其中外循环遍历三角形的线,内循环控制每行打印多少三角形。 For an input of 3, this generated:对于 3 的输入,这会生成:

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

You're very close to a working solution now, instead of making barricade a String with embedded new lines;您现在非常接近一个String的解决方案,而不是使用嵌入的新行来制作barricade make it an array.使它成为一个数组。 I also would prefer sc.nextInt() to hardcoding three calls to Integer.parseInt() and I would further make num1 - num3 an array.我还希望sc.nextInt()硬编码对Integer.parseInt()的三个调用,并且我会进一步使num1 - num3成为一个数组。 Like,喜欢,

int[] nums = { 2, 1, 3 }; // { sc.nextInt(), sc.nextInt(), sc.nextInt() };
String[] barricade = {
        "      *",
        "     **",
        "    ***",
        "   ****",
        "  *****" };
for (int num : nums) {
    for (String line : barricade) {
        for (int j = 0; j < num; j++) {
            System.out.print(line);
        }
        System.out.println();
    }
    System.out.println();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM