首页 > 解决方案 > 将数组保存在文件中

问题描述

编写一个名为 storeArray 的 Java 程序,询问用户方数组的大小(行数和列数相同)。

您的程序应该创建数组,然后用 [0.0, 100.0] 范围内的随机双精度数填充它

创建数组后,您的程序必须将数组保存在名为“routes.txt”的文件中,其中第一行是行数,第二行是列数,数组中的数据从第三行开始直到文件结束。

我的问题是,当我运行程序时,它不会打印行数和列数

Random rnd= new Random();
Scanner input= new Scanner(System.in);

System.out.println("enter the number of row");
                    int rows=input.nextInt();

System.out.println("enter the number of columns");
int columns=input.nextInt();  

double [][] array=new double [rows][columns];

PrintWriter outputFile= new PrintWriter ("D:\\routes.txt");

double min=0.0;
double max=100.0; 
double maxx= (Math.random() * ((max - min) + 1)) + min;

for (int row=0; row<rows ; row++)
    {   System.out.println(array[rows][columns]);
        for (int col=0; col<columns; col++)
        {              
            array[row][col]=maxx;

            System.out.println(array[row][col]);
            outputFile.println(array[row][col]);           
        }            
    }           
outputFile.close();
}

标签: javaarrays

解决方案


像这样更改您的代码

 outputFile.println("rows = " + rows);
        outputFile.println("columns = " + columns);
        for (int row = 0; row < rows; row++) {
           for (int col = 0; col < columns; col++) {
               array[row][col] = min+(Math.random()*max);
                outputFile.println(array[row][col]);
            }
        }
        outputFile.close();

首先,您应该删除该行:

Random rnd= new Random();

因为你从未使用过它。

另外,改变那个

double maxx= (Math.random() * ((max - min) + 1)) + min;

在我的线上

array[row][col] = min + (Math.random() * max);

将为您的矩阵中的每一行提供一个随机数。

另外,如果你想像你一样在主循环中遍历你的数组

System.out.println(array[rows][columns])

您永远不会那样做,因为在每一行上,您仍然没有任何列,因此,您不能那样做,它只能在内部循环中起作用

System.out.println(array[row][col]);

它看起来像你的输出到文件


推荐阅读