我如何在Java的一行中打印字符串块

问题描述 投票:0回答:2

我是Java的新手,我发现了一个活动,需要您根据循环计数来打印字符串块。输入应为:

 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);
    }
  }
}
java
2个回答
0
投票

这是一个有效的脚本:

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,将生成:

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

0
投票

您现在非常接近一个可行的解决方案,而不是将barricade变成带有嵌入式新行的String;使其成为数组。我还希望sc.nextInt()硬编码对Integer.parseInt()的三个调用,并且我将num1-num3进一步设置为数组。喜欢,

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();
}
© www.soinside.com 2019 - 2024. All rights reserved.