2011-10-25 47 views
3

我想用Java写一个捕捉用户整数(假设数据有效)的程序,然后根据整数的大小输出菱形形状,即用户输入5,输出将是:使用循环的Java ascii艺术

--*-- 
-*-*- 
*---* 
-*-*- 
--*-- 

到目前为止,我有:

if (sqr < 0) { 
     // Negative 
     System.out.print("#Sides of square must be positive"); 
    } 

    if (sqr % 2 == 0) { 
     // Even 
     System.out.print("#Size (" + sqr + ") invalid must be odd"); 
    } else { 
     // Odd 
     h = (sqr - 1)/2; // Calculates the halfway point of the square 
     // System.out.println(); 
     for (j=0;j<sqr;j++) {  

      for (i=0;i<sqr;i++) { 

       if (i != h) { 
        System.out.print(x); 
       } else { 
        System.out.print(y); 
       } 

      } 

      System.out.println(); 
     } 

    } 

刚刚输出

--*-- 
--*-- 
--*-- 
--*-- 
--*-- 

任何ID eas,我在考虑减少h的价值,但那只会产生钻石的左手边。

回答

2
void Draw(int sqr) 
     { 
      int half = sqr/2; 
      for (int row=0; row<sqr; row++) 
      { 
       for (int column=0; column<sqr; column++) 
       { 
        if ((column == Math.abs(row - half)) 
         || (column == (row + half)) 
         || (column == (sqr - row + half - 1))) 
        { 
         System.out.print("*"); 
        } 
        else 
        { 
         System.out.print("_"); 
        } 
       } 
       System.out.println(); 
      } 
     } 

好吧,现在这是代码,但正如我看到S.L. Barth的评论我刚刚意识到这是一项家庭作业。因此,我强烈建议您在将其作为最终使用之前理解此代码中编写的内容。随意问任何问题!

+0

您能否向我解释一下Math.abs()函数的作用,我是否认为它给出了任何数字的正值?我已经向您的代码添加了评论,以表明我明白发生了什么。 – Mike

+1

你说得对,迈克,这正是它所做的。 –

2

在你的情况请看下图:

if (i != h) 

这仅着眼于列数(i)和中间点(H)。 您需要查看列号和行号的条件。更确切地说,您需要一个条件来查看列号,行号和中间点列号的距离。
由于这是一个家庭作业问题,所以我给你确定了精确的公式,但是如果你需要,我愿意放弃一些更多的提示。祝你好运!

+0

另外,想想第一行和最后一行是其他行的特例(只有1 * iso 2) – gastush

+0

@ gastush不一定。如果条件由两部分组成,则只有其中一个需要评估为“真”,以便打印*。 –