0

I would like for my program to be in the shape of a triangle with space in between like the photo below. Heres my code so far.

import java.util.Scanner;
public class Triangle {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String space= "          ";
        space.replaceAll("", " ");
        int i = input.nextInt();
        while (i > 0) {
            for (int j = 0; j <1; j++)
                System.out.print("*"+space.substring(0,0)+"*");
            System.out.println();
            i--;
        }
    }

when i run this code the output is this

**

**


**

**

**

**

**

**

**

I would like the output to look like this:

enter image description here

4

3 回答 3

0

首先,您的内部 for 循环没有任何用途。它只运行一次。即使您将其删除,逻辑也会相同。

for (int j = 0; j <1; j++)

其次,我觉得你想做这样的事情:

System.out.print("*"+space.substring(i)+"*");

确保您的字符串比索引 i 足够大

String space= "                                       ";
于 2013-10-11T23:26:10.393 回答
0
    Scanner input = new Scanner(System.in);
    int i=input.nextInt();
    for (int j=0; j<(i-1); j++)
        System.out.print(" ");
    System.out.println("*");
    for (int j=1; j<(i-1); j++)
    {
        for (int k=0;k<(i-1-j); k++)
            System.out.print(" ");
        System.out.print("*");
        for (int k=0;k<(j*2)-1; k++)
            System.out.print(" ");
        System.out.println("*");
    }
    for (int j=0; j<(i*2-1); j++)
        System.out.print("*");
    System.out.println("");
于 2013-10-11T23:28:12.057 回答
0

使用类似的东西String.format("%3s, "*")可以定义宽度(这里:3),因此可以定义输出的空白。如果您添加一些巧妙的代码来定义每行的宽度,您可以省去很多麻烦。

此外,重要的是要知道只有具有固定字母间距的字体才能发挥作用(如 Currier New)。

于 2013-10-11T23:31:51.767 回答