第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在文本文件中保存矩陣

如何在文本文件中保存矩陣

拉風的咖菲貓 2019-04-19 18:15:47
我只想在文本文件中輸入矩陣,但結(jié)果明顯不同。我沒有任何想法。public void saveToTextFile() {    try {        BufferedWriter writer = new BufferedWriter(new FileWriter(new File("matrix.txt")));        for (int i = 0; i < matrix.length; i++) {            for (int j = 0; j < matrix[i].length; j++) {                writer.write(matrix[i][j] + " ");            }            writer.newLine();        }        writer.flush();        writer.close();    } catch (IOException e) {        System.out.println("Error");    }}我預計1 2 34 5 67 8 9但在文件中1 1 15 5 59 9 9
查看完整描述

2 回答

?
慕容3067478

TA貢獻1773條經(jīng)驗 獲得超3個贊

你可以試試這個:

int[][] ints = new int[4][4]; // Let's say you have a 4 * 4 ints array filled like this

        ints[0][0] = 1;
        ints[0][1] = 2;
        ints[0][2] = 3;
        ints[0][3] = 4;

        ints[1][0] = 5;
        ints[1][1] = 6;
        ints[1][2] = 7;
        ints[1][3] = 8;

        ints[2][0] = 9;
        ints[2][1] = 10;
        ints[2][2] = 11;
        ints[2][3] = 12;

        ints[3][0] = 13;
        ints[3][1] = 14;
        ints[3][2] = 15;
        ints[3][3] = 16;

        StringBuilder sb = new StringBuilder(); // String Builder to create the table structure before writing it to the file.

        for (int[] int1 : ints) {
            for (int j = 0; j < int1.length; j++) {
                sb.append(int1[j]).append("\t"); // Add tab to delimite the elements
            }
            sb.append("\r\n"); // Add new line character
        }

        System.out.println(sb);

        Path path = Paths.get("C:\\Users\\youruser\\Documents\\test.txt"); // The path to your file

        Files.write(path, sb.toString().getBytes()); // Writes to that path the bytes in the string from the stringBuilder object.

這將打印像表格的值:

https://img1.sycdn.imooc.com//5cdba03f00012fdd01980063.jpg

查看完整回答
反對 回復 2019-05-15
?
繁星淼淼

TA貢獻1775條經(jīng)驗 獲得超11個贊

對您的方法進行輕微修改:


try {

            int[][] matrix = new int[3][3];

            BufferedWriter writer = new BufferedWriter(new FileWriter(new File("matrix.txt")));


            int num = 1;


            for (int i = 0; i < matrix.length; i++) {

                for (int j = 0; j < matrix[i].length; j++) {

                    writer.write(num + " ");

                    num++;

                }


                writer.newLine();

            }

            writer.flush();

            writer.close();


        } catch (Exception e) {

            System.out.println("Error");

        }


查看完整回答
反對 回復 2019-05-15
  • 2 回答
  • 0 關(guān)注
  • 727 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號