制作正方形网格我错过了什么?

时间:2014-01-14 06:39:22

标签: java

创建一个程序,根据行数和列数生成一组网格框。 样本输入: row = 3和column = 4

示例输出:

 -  -  -  -  
| || || || |
 -  -  -  - 
 -  -  -  - 
| || || || |
 -  -  -  - 
 -  -  -  - 
| || || || |
 -  -  -  - 

我有这个:

import java.util.Scanner;

public class NewClass {
  static Scanner in = new Scanner(System.in); 
  static int row = 0; 
  static int col = 0;

  String[] square = { " -" + //"\n" + "| |" + //"\n" + " -" //"\n" };

  public static void main(String[] args) {
    NewClass nc = new NewClass();

    System.out.println("row:"); 
    row = in.nextInt(); 
    System.out.print("column:"); 
    col = in.nextInt();

    for (int i = 0; i < row; i++) { 
      nc.column(col); 
      System.out.println(); 
    }
  }

  public void column(int col) {
    for (int j = 0; j < col; j++) { 
      System.out.print(square[0]); 
    } 
  }
}

但是输出不正确。我错过了什么?

2 个答案:

答案 0 :(得分:2)

你可以使用两个嵌套的for循环来完成它。内部for循环打印列,out forloop打印换行符以开始新行。

public static void main(String[] args)  {
    Scanner in = new Scanner(System.in); 
    int row = 0, col = 0; 
    System.out.println("row:"); row = in.nextInt(); System.out.print("column:"); col = in.nextInt();

    for (int i = 0; i < row; i++) { 
        for (int j = 0; j < col; j++) { 
            System.out.print(" - ");
        }
        System.out.print("\n");     
        for (int j = 0; j < col; j++) { 
            System.out.print("| |");
        }
        System.out.print("\n");     
        for (int j = 0; j < col; j++) { 
            System.out.print(" - ");
        }
        System.out.print("\n");     
    }
}

输入:rows = 3 cols = 4

输出:

 -  -  -  - 
| || || || |
 -  -  -  - 
 -  -  -  - 
| || || || |
 -  -  -  - 
 -  -  -  - 
| || || || |
 -  -  -  - 

答案 1 :(得分:0)

您可能希望将光标移动到绘图顺序中下一个方块的位置。 这样你就可以得到一个可以绘制自己的方形类和一个控制逻辑,在每次调用方形绘制方法之前放置光标。