Java 画菱形星号
我有一个程序,你输入一个数字,它把它打印成菱形。我让上半部分对齐并计算出,只是不能让下半部分对齐。它应该先增加星号的数量,然后再减少到一个Java 画菱形星号,java,object,asterisk,Java,Object,Asterisk,我有一个程序,你输入一个数字,它把它打印成菱形。我让上半部分对齐并计算出,只是不能让下半部分对齐。它应该先增加星号的数量,然后再减少到一个 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 row
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();
}
}
下半部分的代码如下所示:
space += 2;
for (j = n - 1; j > 0; 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(" ");
}
示例运行:
对于j=n-1;j>0;玩这个。开始/结束较高/较低,并查看结果如何变化。这可能是一个很好的机会来了解我将您的输入移动到选项窗格中的原因??你做了什么来解决眼前的问题?不清楚,因为我讨厌在测试时处理控制台。输入的方法与他所遇到的问题无关。那么,你的答案与什么有关呢?正如我所说的,不清楚你做了什么才真正解决了这个问题。问题是,虽然这个代码片段可以解决这个问题,但确实有助于提高你的文章的质量。请记住,您将在将来回答读者的问题,这些人可能不知道您的代码建议的原因。
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 += 2;
for (j = n - 1; j > 0; 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(" ");
}
}
}
Enter the number of rows: 5
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*