簡體   English   中英

如何將我的數組從 1 行更改為 20x20 正方形? (爪哇)

[英]How do i change my array from being on 1 line to being a 20x20 square? (Java)

我需要將數組的格式更改為顯示為 20x20 正方形的位置。 關於做到這一點的最佳方法的任何想法?

public class MyGrid {

public static void main(String[] args) throws IOException
{
    FileReader file = new FileReader("list.txt");
    int[] integers = new int [400];
    int i=0;
    try {
        Scanner input = new Scanner(file);
        while(input.hasNext())
        {
            integers[i] = input.nextInt();
            i++;
        }
        input.close();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    System.out.println(Arrays.toString(integers));
}

}

try-with-resources語句很好; 我建議利用它來安全清理。 我認為您的Scanner不需要FileReaderFile就足夠了)。 然后每 20 個值打印一個換行符 - 否則打印一個空格; 然后打印值。 喜歡,

int[] integers = new int[400];
try (Scanner input = new Scanner(new File("list.txt"))) {
    int i = 0;
    while (input.hasNextInt()) {
        integers[i] = input.nextInt();
        if (i != 0) {
            if (i % 20 == 0) {
                System.out.println();
            } else {
                System.out.print(" ");
            }
        }
        System.out.printf("%03d", integers[i]);
        i++;
    }
} catch (Exception e) {
    e.printStackTrace();
}

最簡單和最快的方法(對我來說)是:

public class MyGrid {
    public static void main(String[] args) throws IOException {
        FileReader file = new FileReader("list.txt");

        int[] integers = new int[400];
        int[][] table = new int[20][20];
        int m, n, i = 0;

        int tableWidth = table[0].length; // 20 in that case

        try {
            Scanner input = new Scanner(file);
            while(input.hasNext()) {
                int value = input.nextInt();
                integers[i] = value;
                
                m = i / tableWidth; // Row index
                n = i % tableWidth; // Column index
                table[m][n] = value;

                i++;
            }

            input.close();
        } catch(Exception e) {
            e.printStackTrace();
        }

        System.out.println(Arrays.toString(integers));
    }
}

此外,此代碼將適應任何其他表格大小(例如 500、600 或 4237 個元素)。

注意:此代碼將數據存儲在 2D 數組中,但不會在控制台中顯示它。 如果您想在讀取文件時顯示數據,我建議您查看更適合的@Elliott Frisch答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM