猿问

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

我是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);

    }

  }

}


牛魔王的故事
浏览 112回答 2
2回答

撒科打诨

这是一个工作脚本:Scanner sc = new Scanner (System.in);String[] lines = {"&nbsp; &nbsp; &nbsp; *", "&nbsp; &nbsp; &nbsp;**", "&nbsp; &nbsp; ***", "&nbsp; &nbsp;****", "&nbsp; *****"};int input = Integer.parseInt(sc.nextLine());for (int i=0; i < lines.length; ++i) {&nbsp; &nbsp; for (int j=0; j < input; ++j) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.print(lines[i]);&nbsp; &nbsp; &nbsp; &nbsp; System.out.print(" ");&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println();}我们可以在这里使用嵌套循环,其中外循环迭代三角形的线,内循环控制每行打印多少个三角形。对于输入 3,生成:&nbsp; &nbsp; &nbsp; *&nbsp; &nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp; &nbsp;*&nbsp; &nbsp; &nbsp;**&nbsp; &nbsp; &nbsp; **&nbsp; &nbsp; &nbsp; **&nbsp; &nbsp; ***&nbsp; &nbsp; &nbsp;***&nbsp; &nbsp; &nbsp;***&nbsp; &nbsp;****&nbsp; &nbsp; ****&nbsp; &nbsp; ****&nbsp; *****&nbsp; &nbsp;*****&nbsp; &nbsp;*****

茅侃侃

您现在已经非常接近可行的解决方案,而不是制作嵌入新行的解决方案barricade;String使其成为一个数组。我也更喜欢sc.nextInt()将三个调用硬编码到一个数组Integer.parseInt(),并且我将进一步创建num1一个num3数组。喜欢,int[] nums = { 2, 1, 3 }; // { sc.nextInt(), sc.nextInt(), sc.nextInt() };String[] barricade = {&nbsp; &nbsp; &nbsp; &nbsp; "&nbsp; &nbsp; &nbsp; *",&nbsp; &nbsp; &nbsp; &nbsp; "&nbsp; &nbsp; &nbsp;**",&nbsp; &nbsp; &nbsp; &nbsp; "&nbsp; &nbsp; ***",&nbsp; &nbsp; &nbsp; &nbsp; "&nbsp; &nbsp;****",&nbsp; &nbsp; &nbsp; &nbsp; "&nbsp; *****" };for (int num : nums) {&nbsp; &nbsp; for (String line : barricade) {&nbsp; &nbsp; &nbsp; &nbsp; for (int j = 0; j < num; j++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print(line);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println();&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println();}
随时随地看视频慕课网APP

相关分类

Java
我要回答