2017-10-04 62 views
-5

我需要绘制一个正方形,其轮廓全部为*'s,内部填充字符.(点)。 也有输入将决定广场的大小。 这是我到目前为止。 我想我需要一个“如果”的声明,但不知道如何实现这一点。 到目前为止,这位代码将通过BIO用户输入绘制一个正方形*“大纲”的轮廓全部是*,其内部充满了字符“。”。

在此先感谢:)。

public class Main 
{ 
    public static void main(String args[]) 
    { 
     int stars = BIO.getInt(); 
     int a = 1; 

     while (a <= stars) 
     { 
      int starsNumber = 1; 

      while (starsNumber <= stars) 
      { 
       starsNumber = starsNumber + 1; 
       System.out.print('*'); 
      } 

      System.out.println(); 

      a = a +1; 
     } 
    } 
} 
+1

名称混淆了你正在做的事情。通过将“a”作为“垂直坐标”和“starsNumber”作为“水平坐标”来构思概念可能会更容易。然后您可以决定是否使用水平坐标和垂直坐标检查来打印“*”或“。”。你应该为自己计算特定的检查。 – hexaflexagonal

回答

1

我会把这个问题分解成几个步骤。尝试自己搞清楚代码。

您必须打印以下的事情:

  • 广场的顶部。这将是一系列*,长度为stars例如*****
  • stars大量的中间位。这将是一个*开始,然后是一系列。长度为stars - 2,则末尾的a * *...*
  • 广场底部。与顶部完全相同。

for(int i = 0 ; i < stars ; i++) { 
    System.out.print("*"); // top 
} 
System.out.println(); // new line 
for (int j = 0 ; j < stars - 2 ; j++) { 
    System.out.print("*"); // starting * of the middle 
    for (int i = 0; i < stars - 2; i++) { 
     System.out.print("."); // the dots for the middle 
    } 
    System.out.print("*"); // the star at the end of the middle lines 
    System.out.println(); // new line for the next middle line 
} 
for(int i = 0 ; i < stars ; i++) { 
    System.out.print("*"); // bottom 
} 
+0

可以说阿里AK已经完成了一个双重嵌套的循环,并且可以根据“a”和“starsNumber”的值决定是打印一个'*'还是'.''被称为'i'和'j'或'y'和'x')。 – hexaflexagonal

+0

@hexaflexagonal是的,但我试图尽可能直观。如果你愿意,你可以发布另一个答案。 – Sweeper

+0

谢谢,我想我现在得到它。只是其中一个时刻我只是空白。从字面上不知道从哪里开始。谢谢。想知道是否有另一种方式做到这一点? –

0

我用二维数组来存储的char值*和。使用嵌套循环的正方形生成阵列并将其打印出来。生成它时,使用if-else语句来确定是否生成正方形的边框,选择是否放置*或。进入这个数组的索引。

Scanner scanner = new Scanner(System.in); 
System.out.print("Square size: "); 
int size = scanner.nextInt(); 

char[][] square = new char[size][size];       //two-dimen array helps visualize square shape you want 

for (int row=0; row<size; row++) { 
    for (int col=0; col<size; col++) { 
     if (row==0 || row == size-1 || col==0 || col==size-1) { //if border of square 
      square[row][col] = '*'; 
     } 
     else {             //if inside square 
      square[row][col] = '.'; 
     } 
    } 
} 

for (char[] row : square) { 
    System.out.print("\n"); 
    for (char col : row) { 
     System.out.print(col); 
    } 
} 
0

您使用基本循环结构:

for (int row = 0; row < stars; row++) { 
    for (int col = 0; col < stars; col++) { 
     char c; 
     if (CONDITION) 
      c = '*'; 
     else 
      c = '.'; 
     System.out.print(c); 
    } 
    System.out.println(); 
} 

你应该自己弄清楚CONDITION。考虑在您想要打印*而不是.的情况下需要使用xy