在 Java 中输出星号三角形的更简单方法:



所以我完成了一项作业,它有效,但必须有一种更简单的方法来完成此操作;对吗?该程序要求用户输入一个 1-50 之间的数字,并通过根据数字打印星号行来制作等腰三角形。如果数字超出范围,它还应该给出错误,并询问用户是否要再次输入。它已经完成,但对于预期目的来说似乎很长。

public static void main(String[] args) 
{
    //Declare the variables
    //variable to store input character
    int answer; //variable to identify out and the option to run again

    answer = 0;

    //Main body to show description of program and author
    while(answer == JOptionPane.YES_OPTION)
    {
      JOptionPane.showMessageDialog(null, "This program will diplay an isoceles triangle by printing rows of asterisks according to the number entered", "Program by: Ehlert Donald J",
                    JOptionPane.PLAIN_MESSAGE);
      String inputText = JOptionPane.showInputDialog("Input an integer from one to 50: ");
      int inputNumber = Integer.parseInt(inputText);

      if (inputNumber > 50)
       {     
         //Dialog box to ask the user if they want to run the program again
         answer = JOptionPane.showConfirmDialog(null, 
            "Would you like to try and enter a valid number?",
            "Wrong",
            JOptionPane.INFORMATION_MESSAGE);         
        }
      else 
       {
            for(int i=1;i<=inputNumber;i++)
           { 
              for(int j=1;j<=inputNumber;j++)
               {
                  if(j<=i)
                  System.out.print("*");
               }
              System.out.println();
           } 
           for(int i=1;i<=inputNumber;i++)
           {
                for(int j=1;j<=inputNumber;j++)
                {
                   if(j>i) 
                System.out.print("*");
                }
           System.out.println();
           }
          answer = JOptionPane.showConfirmDialog(null, 
            "Would you like to enter another number?",
            "Right",
            JOptionPane.INFORMATION_MESSAGE);
      }
    }
}

我不确定输出应该是什么样子,但这里有一种非常简单的打印"实心"三角形的方法......

public void printTriangle(int size)
{
    char[] line = new char[size];
    for(int i=0;i<size;i++) line[i] = ' ';
    int height = size/2;
    int middle = size/2;
    for(int i=0;i<height;i++)
    {
        line[middle + i] = '*';
        line[middle - i] = '*';
        System.out.println(line);
    }
    line[0] = '*';
    line[size-1] = '*';
    System.out.println(line);
}

如果要打印边框而不是实心三角形,只需使用:

line[middle + i] = '*';
line[middle - i] = '*';
System.out.println(line);
line[middle + i] = ' ';
line[middle - i] = ' ';

这不能正确处理偶数,但你没有提到该怎么做!

最新更新