java - 绘制星号的钻石
问题描述
我有这个程序,您可以在其中输入一个数字并将其打印成菱形。我已经对齐并弄清楚了上半部分,只是无法对齐下半部分。它应该增加星号的数量,然后再减少到一个。
import java.util.Scanner;
public class Diamonds
{
public static void main(String args[])
{
int n, i, j, space = 0;
System.out.print("Enter the number of rows: ");
Scanner s = new Scanner(System.in);
n = s.nextInt();
space = n - 0;
for (j = 0; j <= n; j++)
{
for (i = 0; i < space; i++)
{
System.out.print(" ");
}
System.out.print(" ");
space--;
for (i = j; i <= 2 * j - 1; i++)
{
System.out.print("* ");
}
System.out.println(" ");
}
space = 0;
for (j = n - 1 ; j > 0; j--)
{
for (i = 0; i <= i - n; i++)
{
System.out.print(" ");
}
System.out.print(" ");
space--;
for (i = j; i <= 2 * j - 1; i++)
{
System.out.print(" *");
}
System.out.println(" c ");
space=n-1;
}
}
}
解决方案
我将您的输入移到选项窗格中并清理了其他一些代码:
public static void main(String [] args) {
try {
String amt = JOptionPane.showInputDialog("Enter number of rows:");
int n = Integer.valueOf(amt);
int space = n;
for (int j = 0; j <= n; j++) {
StringBuilder builder = new StringBuilder();
IntStream.range(0, space).forEach(i -> builder.append(' '));
builder.append(" ");
space--;
IntStream.range(j, 2*j).forEach(i -> builder.append("* "));
System.out.println(builder);
}
space++;
for (int j = n - 1; j > 0; j--) {
space++;
StringBuilder builder = new StringBuilder();
IntStream.range(0, space).forEach(i -> builder.append(' '));
builder.append(" ");
IntStream.range(j, 2*j).forEach(i -> builder.append("* "));
System.out.println(builder);
}
} catch (Exception e) {
e.printStackTrace();
}
}