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

Multiple File reading where number of rows are not equal

我有两个数据文件。数据为双精度类型(例如 90.0、25.63)。 File1 由 3 列和几行组成,File2 由 4 列和几行组成。我在一个 Java 程序中分别从两个文件中读取数据,并且 File1 的 Column1 数据与 File2 的 Column1 数据匹配,然后一条消息将显示数据匹配,否则数据不匹配。第一个数据文件中的行数与第二个数据文件中的行数不同。如果在第 4 行中找到匹配项,则第 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

File2 中的行数少于 File1。 File1 和 File2 的第 1 列的所有数据均按升序排列。

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

代码:

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");
            }
        }
    }
}

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

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

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