只需打印一次Unterschiede gefunden:
while(sc.hasNextLine() || sc1.hasNextLine()) {
i++;
try {
text1 = sc.nextLine();``
text2 = sc1.nextLine();
if(!text1.equals(text2)){
System.out.println("Unterschiede gefunden:");
System.out.printf("Zeile %d :\n",i);
System.out.println(text1);
System.out.println(text2);
}
}catch(NoSuchElementException nse) {
text2 = " ";
}
}发布于 2018-12-06 06:09:13
检测一个文本文件是否与另一个文本文件不同。一旦您检测到一个文件行与另一个文件行不同,就通知用户(就像您正在做的那样),并且从您的IF代码块中将从while循环中中断,以便停止处理文件行,例如:
if(!text1.equals(text2)){
System.out.println("Unterschiede gefunden:"); // Difference Detected!
System.out.println("Zeile " + i + ":\n"); // At file line #.
System.out.println("File A: " + text1); // Text line in File A.
System.out.println("File B: " + text2); // Text line in File B.
break; // Break out of the WHILE loop.
}您还考虑到文件A可能比文件B包含更多或更少的行,这很好,但此时您也应该真正退出while循环,因为您现在确定文件A不同于文件B,例如:
// These two variables are used to see which file
// contains more of fewer lines.
int fileACount = 0;
int fileBCount = 0;
// Read the two files...
while (sc.hasNextLine() || sc1.hasNextLine()) {
try {
String fileAText = sc.nextLine();
fileACount++;
String fileBText = sc1.nextLine();
fileBCount++;
if (!fileAText.equals(fileBText)) {
System.out.println("Unterschiede gefunden:");
System.out.printf("Zeile %d :\n", fileACount);
System.out.println(fileAText);
System.out.println(fileBText);
break;
}
}
catch (NoSuchElementException nse) {
// Using a Ternary Operator below so as to
// indicate which file contains more lines.
String fileWithMoreLines = fileACount > fileBCount ? "A" : "B";
System.out.println("Files are different! File " +
fileWithMoreLines + " contains MORE Lines.");
break;
}
}别忘了关闭你的文件。
https://stackoverflow.com/questions/53640143
复制相似问题