![](/img/trans.png)
[英]How to add unique string and the no of count of that string from a bunch of eml file using 2D Array in java
[英]How to add doubles into a 2d array from a file (Java)?
我看到的所有示例都涉及在文件开头指定行和列的数量,但是我正在使用的方法使用以下内容读取文件:
1.0 2.0
3.0 4.0
并使用此数据创建一个二维数组并存储它,而无需指定行数和列数。
这是我编写的代码:
public static double[][] readMatrixFrom(String file) throws FileNotFoundException {
Scanner input = new Scanner(new FileReader(file));
int rows =0;
int columns =0;
while(input.hasNextLine()){
String line = input.nextLine();
rows++;
columns = line.length();
}
double[][] d = new double[rows][columns]
return d;
}
创建2d数组后,我不确定如何添加这些值。 我尝试了这个但是得到了InputMismatchException
。
Scanner s1 = new Scanner(file);
double[][] d = new double[rows][columns]
for (int i= 0;i<rows;i++) {
for (int j= 0;i<rows;j++) {
d[i][j] = s1.nextDouble();
}
}
如果您只想使用基本数组,则可以通过以下方式实现
Scanner input = new Scanner(new FileReader(file));
int row=0;
int col =0;
String s="";
//count number of rows
while(input.hasNextLine()) {
row++;
s=input.nextLine();
}
//count number of columns
for(char c: s.toCharArray()) {
if(c==' ')
col++;
}
col++; // since columns is one greater than the number of spaces
//close the file
input.close();
// and open it again to start reading it from the begining
input = new Scanner(new FileReader(file));
//declare a new array
double[][] d = new double[row][col];
int rowNum=0;
while(input.hasNextLine()) {
for(int i=0; i< col; i++) {
d[rowNum][i]= input.nextDouble();
}
rowNum++;
}
但是,如果您更喜欢使用Java集合,则可以避免再次读取文件。 只需将字符串存储在列表中,然后遍历列表以从中提取元素。
根据您的输入,您的columns = line.length();
返回7而不是2,因为它返回String
长度。
因此,请尝试计算行中的列columns = line.split(" ").length;
同样,在尝试读取输入时,您将索引i
用于第二个for-loop
。 应该像下面这样
for (int i= 0;i<rows;i++) {
for (int j= 0;j<columns;j++) {
d[i][j] = s1.nextDouble();
}
}
为了使用未知大小的数组,您应该将数据读入Collection
(例如List
)。 但是, Collection
仅适用于包装器类型; 因此,如果您确实需要,则需要将元素复制回double
精度数组。 就像是,
public static double[][] readMatrixFrom(String file) throws FileNotFoundException {
Scanner input = new Scanner(new FileReader(file));
List<List<Double>> al = new ArrayList<>();
while (input.hasNextLine()) {
String line = input.nextLine();
List<Double> ll = new ArrayList<>();
Scanner sc = new Scanner(line);
while (sc.hasNextDouble()) {
ll.add(sc.nextDouble());
}
al.add(ll);
}
double[][] d = new double[al.size()][];
for (int i = 0; i < al.size(); i++) {
List<Double> list = al.get(i);
d[i] = new double[list.size()];
for (int j = 0; j < d[i].length; j++) {
d[i][j] = list.get(j);
}
}
return d;
}
我通过在主文件夹中创建一个包含您的内容的文件并像这样运行该文件进行了测试
public static void main(String[] args) {
String file = System.getProperty("user.home") + File.separator + "temp.txt";
try {
System.out.println(Arrays.deepToString(readMatrixFrom(file)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
我得到了(就像我想的那样)
[[1.0, 2.0], [3.0, 4.0]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.