JAVA:If / Else / For Methods?!什么?

时间:2012-03-09 15:42:30

标签: java if-statement java.util.scanner

我甚至无法做基础知识。我做错了什么?

我需要:

  1. 画一个由星星组成的“X”(*)。我必须提示星星中X的宽度。
  2. 我对这项任务的要求是:
    +1 - 提示X的大小 +4 - 绘制星星的X(如果可以绘制实心的恒星,则接收+2)

    顺便说一句,我正在使用 Eclipse

    import java.util.Scanner; 
    
    /*
    * 
    *
    * Description: Draws a X.
    */
    
    public class Tutorial1
    {   
        public static void main(String[] args)
        {   
            Scanner sc = new Scanner(System.in);
            int i,j;
            System.out.print("Enter size of box: 4 ");
            int size = sc.nextInt();
    
            for (i=0; i < size; i++)
            {
                for (j=0; j < size; j++)
                {
                    if ( (i == 0)    // First row
                      || (i == size-1)   // Last row
                      || (j == 0)    // First column
                      || (j == size-1) )     // Last column
                        System.out.print("*");  // Draw star
                    else
                        System.out.print(" ");  // Draw space
                }
                System.out.println();
            }
        }
    } //
    

3 个答案:

答案 0 :(得分:2)

您的程序正确绘制了一个框。

Enter size of box: 4 7
*******
*     *
*     *
*     *
*     *
*     *
*******

您需要更改代码,以便绘制十字形。代码实际上更简单,因为你只有两行而不是四行。

我会从提示中删除4,因为它会让人感到困惑。

Enter size of box: 7
*     *
 *   * 
  * *  
   *   
  * *  
 *   * 
*     *

答案 1 :(得分:2)

您已经知道您的问题。你自己说:“我甚至不能做基础”。

然后学习基础知识。无法解决 THAT

这个网站不是“给我写一段做X的代码”服务。人们只会针对特定问题提出具体问题。你的任务实际上是初学者的东西非常简单一旦你掌握了基本概念。如果做不到这一点,我们可能提供的任何解决方案对您来说都是无用的,因为您甚至不了解问题是如何解决的。更糟糕的是,你的教学很可能会很快注意到你没有自己写的。这会让你变得麻烦 - 你被指控作弊并且还没有学会任何

答案 2 :(得分:1)

这是您需要的骨架。 for循环将遍历表。困难的部分是提出决定打印哪个字符的算法。

public class Tutorial1
{ 
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        int i,j;
        System.out.print("Enter size of box: ");
        size = sc.nextInt();

        Tutorial1 t = new Tutorial1();
        t.printX(size);
    }

    private int _size = 0;

    public void printX(int size) {       
        _size = size;
        for(int row = 0; row < _size;row++) {
            for(int col = 0; col< _size;col++) {
              System.out.print(getChar(row,col));
            }
            System.out.println();
        }
    }

    private String getChar(int row, int col) {
        //TODO: create char algorithm
        //As a pointer, think about the lines of the X independently and
        //how they increment/decrement with the rows
    }
}