行数不相等的多个文件读取



我有两个数据文件。数据为双精度类型(例如,90.0、25.63(。File1 由 3 列和几行组成,File2 由 4 列和几行组成。我在一个 Java 程序中分别从两个文件中读取数据,并且 File1 的 Column1 数据与 File2 的 Column1 数据匹配,然后将显示一条消息,表明数据已匹配,否则数据不匹配。第一个数据文件中的行数与第二个数据文件中的行数不同。如果在第 4 行中找到匹配项,则第 4 行之前的数据将按原样写入,并在第四行记下There is match

例:

文件1:

2.0   0.6258  0.239  1.852
3.0   0.5289  0.782  2.358
5.0   1.2586  2.3658 0.1258
6.0   0.235   0.8547 3.5870

文件2:

5.0  0.8974  1.2358  0.2581  
7.0  0.3258  0.6528  0.6987

文件 2 中的行数低于文件 1 中的行数。文件1和文件2的第一列的所有数据均按升序排列。

我想按原样写2.03.0。然后从 File2 中找到一个匹配项,因此它将写入"找到匹配项",然后从 File1 中6.0按原样写入。然后再次搜索是否找到匹配项,然后再次写下"找到匹配项"。

法典:

import java.io.File;
import java.util.Scanner;
public class F1 {
public static void main(String args[])throws Exception{
Scanner Y =new Scanner(new File("C:\File1.txt"));
Scanner X =new Scanner(new File("C:\File.txt"));
double a=0.0,b=0.0,c,d=0.0,e=0.0,f,g,h;
while (X.hasNext() && Y.hasNext()) {
a = X.nextDouble();
System.out.println(a);//1st row of file1,2nd row of file1.... So lastly some rows at the end of the file will be discard
b = X.nextDouble();
c = X.nextDouble();
d = Y.nextDouble();
System.out.println(e);// 1st row of file2. Every row print as the number of row is less than File1.
e = Y.nextDouble();
f = Y.nextDouble();
g = Y.nextDouble();
if(a==d) {
System.out.println("They are matched");
}
else{
System.out.println("Not Matched");
}
}
}
}

我需要实施任何搜索程序吗?喜欢比纳搜索?在Java中有一个过程Arrays.Binarysearch(array,key)。因此,为了实现这一点,我需要将a变量存储在数组中。然后将此数组的每个单元格与d进行比较。这是正确的程序吗?

如果文件按第一列排序,或者保证具有相同的元素顺序,则您选择的方法将起作用。

如果不是这种情况,您必须首先将文件读入内存(例如,每个文件List<Double>(并比较列表的内容,例如通过对列表进行排序,然后比较元素(同时记住浮点比较可能很棘手(。如果保证每个文件的值是唯一的,则可以使用每个文件的Set并直接比较集合。

最新更新