我试图打印一个二维数组到一个文件



我想在桌面上打印2D数组到txt文件。重要的是,输出以某种方式格式化,即在代码中,因为它表示行和座位。

代码:

package vaja15;
import java.util.*;
import java.io.PrintWriter;
import java.io.File;
import java.io.FileNotFoundException;
public class Vaja15 
{
    public static void main(String[] args) throws FileNotFoundException 
    {
        System.out.println("Vnesi velikost dvorane (vrste/sedezi):  ");
        Scanner sc = new Scanner(System.in);
        Random r  = new Random();
        int vrst = sc.nextInt();
        int sedezev = sc.nextInt(); 
        int [][] dvorana  = new int [vrst][sedezev];
        File  file = new File ("C:/users/mr/desktop/dvorana.txt");

        for(int i = 0; i<dvorana.length; i++)
        {
            System.out.println();
            for (int j = 0; j<dvorana.length; j++)
            {
                dvorana [i][j] = r.nextInt(3);  
                System.out.print(dvorana[i][j]);
                PrintWriter out = new PrintWriter(file);
                out.println(dvorana[i][j]);
                out.close();
            }   
        }
     }
 }

你不应该在循环中打开和关闭一个文件:在循环之前打开一个文件,写你的数组,关闭文件。否则,它将一遍又一遍地覆盖文件。

试试这个:

PrintWriter out = new PrintWriter(file);
for(int i = 0; i<vrst; i++)
{
    System.out.println();
    out.println();
    for (int j = 0; j<sedezev; j++)
    {
        dvorana [i][j] = r.nextInt(3);  
        System.out.print(dvorana[i][j]);          
        out.print(dvorana[i][j]);
    }   
}
out.close();

试试下面的想法:

try {
  File file = new File(path);
  FileWriter writer = new FileWriter(file);
  BufferedWriter output = new BufferedWriter(writer);
  for (int[] array : matrix) {
    for (int item : array) {
       output.write(item);
       output.write(" ");
    }
    output.write("n"); 
  }
  output.close();
} catch (IOException e) {
}

相关内容

  • 没有找到相关文章

最新更新