繁体   English   中英

带扫描仪的Java打印表

[英]Java print table with scanner

我正在尝试通过扫描仪和行打印带有列的表格。 当然,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]);
            }
        }
    }

}

您已经接近了,但是使问题复杂化了。 无需将结果存储在数组或缓冲区字符串中。 您可以不使用换行符而使用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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM