正如标题所述,我在画这个沙漏形图时遇到了问题。目标是让用户选择行数(必须是奇数和正数),然后用该信息绘制沙漏。顶部和底部的行将有相同数量的星号,因为有行。
应该看起来像这样:
*******
*****
***
*
***
*****
*******
这是我到目前为止的代码:
public static void main(String[] args)
{
double nRows;
Scanner console = new Scanner(System.in);
System.out.print("Please enter an odd-number of output-lines (enter zero to exit the program): ");
nRows = console.nextDouble();
for(int row=1; row<=nRows; row++ )
{
for(int column = 1; column<=nRows-row; column++)
System.out.print(" ");
for(int column = 1; column<= row*2-1; column++)
System.out.print("*");
System.out.println();
}
}
打印底部三角形。我遇到的问题是找到打印上半部分的方程。我假设一旦我弄清楚了上半部分的代码,我将不得不使用if语句来告诉它何时在上半部分和下半部分之间切换?
如果有任何帮助,我将不胜感激。
编辑:更新了变量,使其更易于阅读。
就我所听到的,以下是我的理解:
for( int row = nRows; row>=1; row--)
{
for ( int column = 1; column<=nRows-ir; column++)
System.out.print(" ");
for ( int column = 1; column<=row*2-1; column++)
System.out.print("*");
System.out.println();
}
我假设"ir"代表列,"ic"代表行(有点令人困惑)。没有方程可以让它生成顶部,你所要做的就是用生成底部的相同代码并以相反的顺序进行迭代。这可以通过使ic开始为最大值并使其递减而不是递增来实现。我想包括我自己的代码片段,但我读起来有点麻烦。(请按所代表的内容命名变量。例如,行和列而不是ic和ir)
希望我帮到你!
这行得通:
public static void main(String args[]) {
int nRows;
Scanner console = new Scanner(System.in);
System.out.print("Please enter an odd-number of output-lines (enter zero to exit the program): ");
nRows = console.nextInt();
for(int i=0; i < nRows/2; i++ ) {
for(int j = nRows - i; j < nRows; j++) {
System.out.print(" ");
}
for(int j = 0; j < nRows - 2*i; j++) {
System.out.print("*");
}
System.out.println();
}
for(int i=0; i < (nRows+1)/2; i++ )
{
for(int j = 1; j <= nRows/2 - i; j++)
System.out.print(" ");
for(int j = 0; j <= i*2; j++)
System.out.print("*");
System.out.println();
}
}
试着看看这个
外部for循环将决定沙漏的高度。内部for循环将打印*
以显示模式。
希望这能帮助到其他可能需要的人。
public static void hourGlass(int size) {
// 2 for loops only
int dimension = (size * 2) - 1, space = 0, stars = size - 1, printed = 0;
for(int i=0; i<dimension; i++) {
int actual = space;
for (int j=dimension; j > 0; j--) {
if(actual > 0) {
System.out.print(" ");
actual--;
}
else {
System.out.print("*");
if(stars==printed) {
actual = space;
printed = 0;
} else {
actual = 1;
printed++;
}
}
}
if(i <= size-2) { // will pattern spaces and stars from top to middle
space++;
stars--;
}
else { // will pattern spaces and stars from middle to top
space--;
stars++;
}
System.out.println();
}
}