【问题标题】:Java print table with scanner带扫描仪的 Java 打印表
【发布时间】:2019-07-27 13:41:20
【问题描述】:

我正在尝试通过扫描仪和行打印包含列的表格。当然,for 循环应该从 0 开始,但我希望它从 1 开始计数以进行打印。请帮我正确打印代码。我得到空值和数字金字塔。

Output needed when n = 4 inputted:
    1    1    1    1
    2    2    2    2
    3    3    3    3
    4    4    4    4

import java.util.Scanner;

public class Testing {

    public static void main(String[] args) {

        System.out.print("Type any variable?");
        Scanner input = new Scanner(System.in);

        int n = input.nextInt();

        String[] arr = new String[n + 1];
        String s = "";
        for (int count = 1; count <= 10; count++) {
            for (int col = 1; col <= n; col++) {
                s = count + "\t";
                arr[col] += s;
                System.out.println(arr[col]);
            }
        }
    }

}

【问题讨论】:

  • 我不明白你的硬编码&lt;= 10 ...为什么是10?另外,您知道System.out.println()System.out.print() 之间的区别吗?如果没有,那么这是您需要为此任务学习的一件事,或者至少非常方便。
  • 我以10为例。
  • 那么你没有清楚地描述输出的要求。例如,对于输入值“20”,您会期望什么?
  • 再次,我以10为例。
  • 什么例子?

标签: java rows col


【解决方案1】:

你已经接近了,但你把问题复杂化了。无需将结果存储在数组或缓冲区字符串中。您可以使用print 写入屏幕而无需换行,并且在每个内部循环结束时,您可以使用println 移动到下一行。

int n = input.nextInt();
for (int count = 1; count <= n; count++) {
    for (int col = 1; col <= n; col++) {
        System.out.print(count + "\t");
    }
    System.out.println();
}

【讨论】:

    猜你喜欢
    • 2018-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-15
    • 2016-03-01
    • 1970-01-01
    相关资源
    最近更新 更多