简体   繁体   中英

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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