该程序需要从 1 个文本文件中读取“信用卡”号码,将它们与第二个文本文件进行比较,如果有匹配,则将其与第三个进行比较,然后显示所有 3 个文本文件中匹配的号码。
我遇到了很多麻烦,无法弄清楚出了什么问题。任何帮助将不胜感激。
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.FileReader;
import java.io.BufferedReader;
public class Search {
public static void main(String[] args) throws IOException { //main method
boolean match = false;
String creditNumber = null;
BufferedReader reader1 = new BufferedReader(new FileReader("creditCards1.txt"));
creditNumber = reader1.readLine();
while(match = false & creditNumber != null){
System.out.println(creditNumber);
boolean confirm = false;
confirm = searchTwo(creditNumber);
if(confirm == true){
confirm = searchTwo(creditNumber);
System.out.println(confirm);
break;
}
reader1.close();
}
}
public static boolean searchTwo(String creditNumber) throws IOException { //method for searching the 2nd text file
boolean match = false;
String creditNumber2 = null;
BufferedReader reader2 = new BufferedReader(new FileReader("creditCards2.txt"));
creditNumber2 = reader2.readLine();
while(match = false & creditNumber != null){
boolean confirm = false;
confirm = searchThree(creditNumber2);
if(confirm == true & creditNumber2.equals(creditNumber)){
match = true;
System.out.println(creditNumber2);
}
creditNumber2 = reader2.readLine();
}
reader2.close();
if(match = true || creditNumber2 == null){
return match;
}
return match;
}
public static boolean searchThree(String creditNumber) throws IOException { //method for searching the 3rd text file
boolean match = false;
String creditNumber3 = null;
BufferedReader reader3 = new BufferedReader(new FileReader("creditCards3.txt"));
creditNumber3 = reader3.readLine();
while(match = false & creditNumber != null){
if(creditNumber3.equals(creditNumber)){
match = true;
break;
}
creditNumber3 = reader3.readLine();
}
reader3.close();
if(match = true || creditNumber3 == null){
return match;
}
return match;
}
}
最佳答案
我发现这里有一些问题。
您永远不会在
main
中设置match = true
,因此它将永远循环。-
confirm = searchTwo(creditNumber); if(confirm == true){ confirm = searchTwo(creditNumber); System.out.println(confirm); break; }
这段代码是多余的。
searchTwo()
仅当searchThree()
返回true
时才返回 true。 您没有检查
while
循环中的相等性,您只是设置变量。while(match = false & creditNumber != null)
应更改为:
while(match == false && creditNumber != null)
您需要在 while 循环内读取新行,而不仅仅是在其外部读取一次。按照目前的方式,您只能读取文件的第一行。
关于java - 读取 3 个文本文件并找到匹配的数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31949263/