【问题标题】:I would like some help making a table that prints 1-100我需要一些帮助来制作一张打印 1-100 的表格
【发布时间】:2014-10-06 20:10:31
【问题描述】:

以下是我的作业要求:

  1. 打印出 1 到 100 之间的所有数字,每行 10 个数字使用制表符等间距。
  2. 最多使用 2 个循环和 1 个 if 语句。

我非常了解需要如何完成此操作,但我只是在想办法在每 10 个数字后开始一个新行时遇到了麻烦。

这是我目前所拥有的:

import java.util.Scanner;
public class Table {
    public static void main (String[] args) {
        int counter, value;
        counter = 1;
        value = 0;
        while (value < 100) {
            value += counter;
            System.out.print(value + "\t");
        }
    }
}

【问题讨论】:

  • Scanner 是干什么用的?
  • 糟糕!当我为班级做项目时,我只是复制并粘贴一个旧程序。

标签: java loops if-statement computer-science


【解决方案1】:

要开始新行,请打印 '\n' 字符。

if ((value % 10) == 0) {
    System.out.print("\n"); // Or really, just System.out.println();, since that makes a new line.
}

【讨论】:

  • 感谢您的帮助 :) 我没想到要使用 % 运算符
  • @TheAventador 也,如果您认为您的问题已得到充分回答,请“接受”答案,以便其他人知道它已被处理(点击投票箭头下方的绿色“检查”) .否则,我们可能会继续用答案轰炸你。 ;) (但如果你想要更多的视角,不用担心打开它。)
【解决方案2】:

有两种方法可以解决这个问题:

  1. 遍历表格中的每一行,并为每一行打印每个数字 x1、x2、x3、x4、...、x + 10,后跟换行符。
  2. 逐个处理所有数字,并在每个数字之后检查它是否是十的整数(想想模算术),如果是,则在其后面加上一个换行符。

【讨论】:

    【解决方案3】:

    由于您已经知道需要迭代的数字范围,我将使用一个 for 循环,从 0 开始到

    您的循环中缺少增量 counter++。

    在 for 循环中使用 if 语句 if (i % 10 = 0) {System.out.println(value + "/n";}, else System.out.println(value + " ");

    祝你的任务好运。

    【讨论】:

      猜你喜欢
      • 2011-08-24
      • 1970-01-01
      • 1970-01-01
      • 2018-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-23
      • 1970-01-01
      相关资源
      最近更新 更多