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

如何在Java乘法表中移除左上角三角区域

Java乘法表移除左上角三角区域的修改方案

你的核心需求是隐藏乘法表中左上角的三角区域,本质就是当列号j小于行号i时,不输出乘积,而是输出对应宽度的空格,这样就能保留右下三角的内容,同时保持表格对齐。

直接修改你现有代码中的内层循环即可,以下是调整后的完整代码:

import java.util.Scanner;

public class MultiTable {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.printf("%s", "Please enter a positive max. number: ");
    int maxnum = in.nextInt();
    System.out.printf("\n");
    // 修正输入验证:正整数排除0,改成<=0
    while (maxnum <= 0) {
      System.out.printf("%s\n\n", "Please enter a positive max. number: ");
      maxnum = in.nextInt();
    }
    int i = 0;
    int j;
    // 打印表头
    System.out.printf("%10d", i);
    for (i = 0; i <= maxnum - 1; i++) {
      System.out.printf("%5d", i + 1);
    }
    System.out.printf("\n-----");
    for (i = 0; i <= maxnum; i++) {
      System.out.printf("-----");
    }
    System.out.printf("\n");
    // 打印乘法表主体
    for (i = 0; i <= maxnum; i++) {
      System.out.printf("%3d%2s", i, " |");
      for (j = 0; j <= maxnum; j++) {
        // 核心修改:j < i时输出空格,否则输出乘积
        if (j < i) {
          System.out.printf("%5s", "");
        } else {
          System.out.printf("%5d", i * j);
        }
      }
      System.out.printf("\n");
    }
    in.close(); // 关闭Scanner避免资源泄漏
  }
}

关键修改点说明:

  • 三角区域隐藏逻辑:在内层循环中增加if (j < i)的判断,当列号小于行号时,用%5s输出5个空格(和数字的宽度一致,保证表格对齐),否则正常输出乘积。
  • 输入验证优化:把原代码的while (maxnum < 0)改成while (maxnum <= 0),因为0不是正整数,符合题目要求。
  • 资源释放:添加in.close()关闭Scanner,养成良好的编码习惯。

测试输入3,输出效果如下:

0    1    2    3
-------------------------------
  0  |    0    0    0    0
  1  |         1    2    3
  2  |              4    6
  3  |                   9

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 00:52:24