You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java实现用户输入自定义边框与内部字符的矩形框问题

解决矩形边框与内部填充字符的输出问题

你当前的代码能生成全边框的矩形,但缺少对行的分支判断,导致无法区分首尾行和中间行的字符输出逻辑。要实现需求,只需要在外层循环中对每行的位置做判断,分别处理首尾行和中间行的输出即可。

修改后的完整代码如下:

// Below this comment: import the Scanner
import java.util.Scanner;
public class Box {
   public static void main(String[] args) {
      // Below this comment: declare and instantiate a Scanner
      Scanner scnr = new Scanner(System.in);

      // Below this comment: declare any other variables you may need
      int width;
      int height;
      char border;
      char interior;


      // Below this comment: collect the required inputs
      System.out.println("Enter width    : ");
      width = scnr.nextInt();
      System.out.println("Enter height   : ");
      height = scnr.nextInt();
      System.out.println("Enter border   : ");
      border = scnr.next().charAt(0);
      System.out.print("Enter interior : ");
      interior = scnr.next().charAt(0);


      // Below this comment: display the required results
      for (int j = 0; j < height; j++) {
          // 处理首行和末行:全边框字符
          if (j == 0 || j == height - 1) {
              for (int i = 0; i < width; i++) {
                  System.out.print(border);
              }
          } else {
              // 中间行:先输出左侧边框
              System.out.print(border);
              // 输出内部填充字符,数量为宽度减2(去掉左右两个边框)
              for (int i = 0; i < width - 2; i++) {
                  System.out.print(interior);
              }
              // 输出右侧边框
              System.out.print(border);
          }
          // 每行结束换行
          System.out.println();
      }
   }
}

关键逻辑说明

  • 外层循环控制行数,通过j == 0判断首行,j == height - 1判断末行,这两行直接循环输出width个边框字符。
  • 中间行的处理分为三部分:先输出1个左侧边框字符,然后循环输出width-2个内部填充字符(因为左右各占一个位置),最后输出1个右侧边框字符。
  • 每行结束后执行System.out.println()完成换行。

示例效果

当输入宽7、高5,边框字符X、内部字符O时,输出如下:

XXXXXXX
XOOOOOX
XOOOOOX
XOOOOOX
XXXXXXX

内容的提问来源于stack exchange,提问作者comingundone

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 19:45:32