因此,我完成了一项作业,并且可以运行,但是必须有一种更简单的方法来执行此操作;对?该程序要求用户输入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);
}
}
}
答案 0 :(得分:1)
我不确定输出应该是什么样,但这是打印“实心”三角形的一种非常简单的方法...
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] = ' ';
这不能正确处理偶数,但是您没有提及该怎么做!