簡體   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