java - 将数组保存在文件中
问题描述
编写一个名为 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();
}
解决方案
像这样更改您的代码
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]);
它看起来像你的输出到文件
推荐阅读
- vb.net - 将 VS 2005 项目转换为 VS 2017 后的类实例化问题
- angular - 能够以角度反应形式在表格中动态添加和删除行
- html - Webstorm 代码检查无法解析服务文件
- c# - 尝试在 Unity 中制作火车但遇到一些问题
- php - 使用php返回MySQL存储过程结果集
- angular - 使用路由器测试子组件的内容
- python - 回调返回 NameError - Scrapy
- vue.js - Vue.js 如何修复错误:Uncaught TypeError: data.filter is not a function in my code?
- c# - 从控制器获取价值以在 ASP.NET MVC 中查看
- oracle - ORA-00907: 缺少右括号(所有括号都在那里!)