1
import java.util.Scanner;

public class diamond {
    public static void main (String[] args){

        Scanner scan = new Scanner(System.in);

        System.out.println("Please enter an integer");
        int lines = scan.nextInt();

        for(int counter = 1; counter <= lines; counter++)
        {   
            if (counter%2 != 0)
            {
                for(int count2 = 1; count2 <= counter; count2++){
                System.out.print("*");
                }
            System.out.println();
            }
        }
    }
}

我应该向用户询问几行并输出一个由星号组成的菱形,这些行高。我需要一些帮助来弄清楚如何使星号居中。我知道字符串有一些 String.utils 方法或其他东西,但输出是基于 for 循环的,所以我认为这在这里并不适用。如果是这样,请务必让我知道。

4

2 回答 2

1

您需要在每行之前打印一定数量的空格。然后,你需要另一个 for 循环来做相反的事情。试试这个代码:

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    System.out.println("Please enter an integer ");
    int lines = scan.nextInt();

    for (int counter = 1; counter <= lines; counter++) {

        if (counter % 2 != 0) {
            for (int i = 0; i < lines - (counter / 2) - 3; i++) {
                System.out.print(" ");
            }
            for (int count2 = 1; count2 <= counter; count2++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
    for (int counter = lines - 1; counter >= 1; counter--) {

        if (counter % 2 != 0) {
            for (int i = 0; i < lines - (counter / 2) - 3; i++) {
                System.out.print(" ");
            }
            for (int count2 = 1; count2 <= counter; count2++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}
于 2013-09-29T02:17:27.753 回答
1

我认为你应该准备一个字符串在每一行上打印出来,然后你就会确切知道它有多少个字符,当行增加时,删除字符串中心的两个'*'并在它前面添加一个“” ,然后再次打印出来。

于 2013-09-29T02:18:39.343 回答