用 ‘+’ ‘-’ ‘|’ 做边界,画出多个表格
1、控制台画格
用户输入格子的行数、列数、每个格子的宽度、高度,画出一组格子。
如下:
先画一个宽(w) 4,高(h) 1 的格子(边界不算在该格子的尺寸内),然后再把它画出 2 行(row),3 列(col)。
以下程序是先开一个大的数组 char[][] cc = new char[row * (h+2)][col * (w+2)] 数组可以开的大一些,以防越界,以下程序是开的刚好的数组。
找出单位格子的边界,以及每个格子的起始位置、终止位置,把他们在数组中的相应位置赋值为相应的‘+’、‘-’、‘|’即可,最后显示输出该数组即可。
相应编程如下:
// 2017-03-17 by 迷糊狐狸
import java.util.Scanner;
public class MyWork {
static Scanner scan = new Scanner(System.in);
//开一个数组,数组大小根据行数、列数以及单个表格的宽、高决定
//以单个表格为单位画出所需表格数
static void block(int row, int col, int w, int h){
char[][] cc = new char[row * (h+2)][col * (w+2)];
for(int i=0; i<row; i++){
for(int j=0; j<col; j++){
one_block(cc, j*((w+2)-1), i*((h+2)-1), w+2, h+2);
}
}
show(cc);
}
//确定每个表格的横、纵的起始位置已经画线宽度
static void one_block(char[][] cc, int x, int y, int w, int h){
draw_line_x(cc, x, y, w);
draw_line_x(cc, x, y+h-1, w);
draw_line_y(cc, x, y, h);
draw_line_y(cc, x+w-1, y, h);
}
//每个表格的每条横线的两端为加号,中间为减号
static void draw_line_x(char[][] cc, int x, int y, int len){
cc[y][x] = '+';
for(int i=0; i<len-2; i++)cc[y][x+i+1] = '-';
cc[y][x+len-1] = '+';
}
//每个表格的每条纵线两端为加号,中间为竖线
static void draw_line_y(char[][] cc, int x, int y, int wid){
cc[y][x] = '+';
for(int i=0; i<wid-2; i++)cc[y+i+1][x] = '|';
cc[y+wid-1][x] = '+';
}
//显示出该数组
static void show(char[][] cc){
for(int i=0;i<cc.length;i++){
for(int j=0;j<cc[i].length;j++){
System.out.print((cc[i][j]==0)? ' ' : cc[i][j]);
}
System.out.println();
}
}
public static void main(String[] args) {
while(true){
try{
System.out.println("请输入表格行数:");
int row = Integer.parseInt(scan.nextLine().trim());
if(row<1) throw new Exception();
System.out.println("请输入表格列数:");
int col = Integer.parseInt(scan.nextLine().trim());
if(col<1) throw new Exception();
System.out.println("请输入单位表格的宽度:");
int width = Integer.parseInt(scan.nextLine().trim());
if(width<1) throw new Exception();
System.out.println("请输入单位表格的高度:");
int height = Integer.parseInt(scan.nextLine().trim());
if(height<1) throw new Exception();
block(row, col, width, height);
break;
}catch(Exception e){
System.out.println("输入有误!");
}
}
}
}
注意,用户在自行确定表格的行数、列数以及单位表格的宽度、高度时均不得小于 1,
否则视为输入失误,将重新输入。
程序运行结果如下:
正确示例:
错误示例1(输入的不是数字):
错误示例2(输入的数字小于1):