简体   繁体   English

带扫描仪的Java打印表

[英]Java print table with scanner

I am trying to print a table with columns through a scanner and rows. 我正在尝试通过扫描仪和行打印带有列的表格。 Of course, the for loop should start at 0, but I want it to start count by 1 for print out. 当然,for循环应从0开始,但是我希望它从1开始计数以打印出来。 Please help me correctly print the code. 请帮助我正确打印代码。 I am getting null and a pyramid of numbers. 我得到的是空值和数字金字塔。

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]);
            }
        }
    }

}

You're close, but you're over complicating the problem. 您已经接近了,但是使问题复杂化了。 There's no need to store the result in an array, or a buffer string. 无需将结果存储在数组或缓冲区字符串中。 You can use print to write to the screen without making a newline, and at the end of each inner loop, you can use println to move to the next line. 您可以不使用换行符而使用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