我有两个数据文件。数据是双精度类型。文件1由3列和几行组成,文件2由4列和几行组成。我在一个Java程序中分别从两个文件中读取数据,并且File1的第1列数据与File2的第1列数据匹配,然后出现一条消息,显示数据已匹配,否则数据不匹配。我的代码就是这样
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:\\R5_M.txt"));
Scanner X =new Scanner(new File("C:\\R5_O.txt"));
double a=0.0,b=0.0,c,d=0.0,e=0.0,f,g,h;
if(a==d) {
while (X.hasNext()) {
a = X.nextDouble();
b = X.nextDouble();
c = X.nextDouble();
}
while (Y.hasNext()) {
d = Y.nextDouble();
e = Y.nextDouble();
f = Y.nextDouble();
g = Y.nextDouble();
}
System.out.println("They are matched");
}
else{
System.out.println("Not Matched");
}
}
}
仅一次输出为They are matched
。但是它应该写入等于行数的输出。如果我在两个数据文件中都有10行,并且匹配了6个数据,而没有匹配4个数据,则得到输出,它们匹配6次,不匹配4次。
一个明显的原因是两个循环都在该范围内结束,因此a,b,c,d,e,f,g的更改值仍保留在范围内,或者我应该说它们在每次迭代中都被覆盖如果我在while循环外调用a和d,则在这种情况下它仅返回最后一个值第十个值。那么我应该在哪里写下if语句来比较每个值?
答案 0 :(得分:2)
您需要这样做
public static void main(String args[])throws Exception{
Scanner Y =new Scanner(new File("C:\\R5_M.txt"));
Scanner X =new Scanner(new File("C:\\R5_O.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();
b = X.nextDouble();
c = X.nextDouble();
d = Y.nextDouble();
e = Y.nextDouble();
f = Y.nextDouble();
g = Y.nextDouble();
if(a==d) {
System.out.println("They are matched");
}
else{
System.out.println("Not Matched");
}
}
答案 1 :(得分:1)
一种有效的方法是使用映射存储两个文件中的每个条目,然后将两者进行比较:
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
Scanner Y = new Scanner(new File("C:\\R5_M.txt"));
Scanner X = new Scanner(new File("C:\\R5_O.txt"));
double a = 0.0, b = 0.0, c, d = 0.0, e = 0.0, f, g, h;
// Create a map to hold the values from each file
HashMap<String, Double> yList = new HashMap<>();
HashMap<String, Double> xList = new HashMap<>();
// Read in the data from both files
while (Y.hasNext()) {
// This will place the values into the HashMap. The first value is whatever "key"
// you want to use, the second is the value itself.
yList.put("a", Y.nextDouble());
yList.put("b", Y.nextDouble());
yList.put("c", Y.nextDouble());
}
while (X.hasNext()) {
xList.put("a", X.nextDouble());
xList.put("b", X.nextDouble());
xList.put("c", X.nextDouble());
}
// Now, you can compare values in both maps
// The HashMap has a list called entrySet that allows you to iterate over all
// of the entries in the list
for (Map.Entry<String, Double> entry : yList.entrySet()) {
// This will check if the current entry's key/value pair matches the identical
// key/value pair in the xList map.
if (entry.getValue() == xList.get(entry.getKey()).doubleValue()) {
System.out.println(entry.getKey() + " matches!");
} else {
System.out.println(entry.getKey() + " does NOT match!");
}
}
}
}
这也可以用来从每个文件读取未知数量的条目。