逐行打印数组内容按列
这是代码:
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ReadFileContents {
public static void main(String[] args) throws IOException {
Scanner s = new Scanner(new File("rfg.txt"));
List<float[]> list = new ArrayList<float[]>();
while (s.hasNextLine()) {
String[] line = s.nextLine().split(" ");
list.add(new float[] { Float.parseFloat(line[0]),Float.parseFloat(line[1]),Float.parseFloat(line[2]) });
}
int numberOfRows = list.size();
int numberOfColumns = 3;
float[][] floatValues = new float[numberOfRows][numberOfColumns];
for (int i = 0; i < numberOfRows; i++) {
floatValues[i] = list.get(i);
System.out.println(floatValues[i][0] + " " + floatValues[i][1] + " " + floatValues[i][2]);
}
}
}
这是 .txt 文件:
5.1 3.5 1.4 2.0
4.9 3.0 1.4 40.1
4.7 3.2 1.3 1.4
4.6 3.1 1.5 5.1
5.0 3.6 1.4 4.1
5.4 3.9 1.7 9.4
4.6 3.4 1.4 4.5
5.0 3.4 1.5 3.51
4.4 2.9 1.4 4.0
4.9 3.1 1.5 1.45
它仅提供 3 列的 o/p:
但我想打印与文件中给出的尺寸相同的文件(具有“n*m”尺寸的文件)。尺寸可以根据给定的文件进行更改。
here is code:
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class ReadFileContents {
public static void main(String[] args) throws IOException {
Scanner s = new Scanner(new File("rfg.txt"));
List<float[]> list = new ArrayList<float[]>();
while (s.hasNextLine()) {
String[] line = s.nextLine().split(" ");
list.add(new float[] { Float.parseFloat(line[0]),Float.parseFloat(line[1]),Float.parseFloat(line[2]) });
}
int numberOfRows = list.size();
int numberOfColumns = 3;
float[][] floatValues = new float[numberOfRows][numberOfColumns];
for (int i = 0; i < numberOfRows; i++) {
floatValues[i] = list.get(i);
System.out.println(floatValues[i][0] + " " + floatValues[i][1] + " " + floatValues[i][2]);
}
}
}
here is .txt file:
5.1 3.5 1.4 2.0
4.9 3.0 1.4 40.1
4.7 3.2 1.3 1.4
4.6 3.1 1.5 5.1
5.0 3.6 1.4 4.1
5.4 3.9 1.7 9.4
4.6 3.4 1.4 4.5
5.0 3.4 1.5 3.51
4.4 2.9 1.4 4.0
4.9 3.1 1.5 1.45
it gives o/p of only 3 columns:
but i want to print the file which is having the same dimension as given in file(file with "n*m" dimension). dimensions can be changed as per the given file.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您仅从文本文件中读取 3 列。如果列数是动态的,那么您可以使用如下循环:
这样列数就成为文件中的列数。
You are only reading 3 columns from the text file. If the number of columns is dynamic then you can use a loop like this:
This way the number of columns become the number of columns in the file.
如果我理解正确的话,您想解析带有浮点值矩阵的文件。您希望通过读取文件并将其存储在
float[][]
中来确定尺寸。我相信你想要的是:If I understand correctly, you want to parse a file with a matrix of float values. You want to determine the dimensions by reading the file and storing them in a
float[][]
. Here what I believe you want: