试题 算法提高 栅格打印问题

问题描述
  编写一个程序,输入两个整数,作为栅格的高度和宽度,然后用“+”、“-”和“|”这三个字符来打印一个栅格。
  输入格式:输入只有一行,包括两个整数,分别为栅格的高度和宽度。
  输出格式:输出相应的栅格。
  输入输出样例
样例输入
3 2
样例输出
±±+
| | |
±±+
| | |
±±+
| | |
±±+

资源限制
时间限制:1.0s 内存限制:512.0MB

思路
使用双层for循环控制高度和宽度,逐层打印,最后一行以及每行的最后一个字符特殊处理

代码块

import java.util.Scanner;
public class Main {
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);
		
		int h = sc.nextInt();
		int w = sc.nextInt();
		
		f(h, w);
		
	}

	
	static void f(int h, int w){
		if(h <= 0 || w <= 0)return;
		
		//打印并输出
		for(int i = 0; i < h; i++){//控制高度
			for(int j = 0; j < w; j++){//控制宽度
				System.out.print("+-");
			}
			//补充每行最后一个“+”
			System.out.println("+");
			for(int k = 0; k < w; k++){
				System.out.print("| ");
			}
			//补充每行最后一个“|”
			System.out.println("|");
		}
		
		//补充最后一行
		for(int j = 0; j < w; j++){
			System.out.print("+-");
		}
		System.out.println("+");
	}
}

在这里插入图片描述

发布了86 篇原创文章 · 获赞 3 · 访问量 1386

猜你喜欢

转载自blog.csdn.net/wnamej/article/details/105458100
今日推荐