我正在尝试在包含给定字符串集的文本文件中附加任何行。我创建了一个测试文件,在其中放置了其中一个字符串。我的代码应该在与文本文件中的前一行相同的行上打印包含这些字符串之一的文本文件中的任何行。这是我的代码:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class AppendIfFromFileScanner {
public static void main(String args[]) {
File file = new File("C:\\Users\\frencke\\workspace\\Testing Stuff\\Append Tetsing\\file3.txt");
ArrayList<String> lines = new ArrayList<String>();
String delima = "\\s+\\s+\\s+\\s+\\s+&\\s+";
String delimb = "\\s+\\s+\\s+\\s+\\s+\\+\\s+";
String delimc = "\\s+\\s+\\s+\\s+\\s+z\\s+";
String delimd = "\\s+\\s+\\s+\\s+\\s+1\\s+";
String delime = "\\s+\\s+\\s+\\s+\\s+2\\s+";
String delimf = "\\s+\\s+\\s+\\s+\\s+3\\s+";
String delimg = "\\s+\\s+\\s+\\s+\\s+4\\s+";
String delimh = "\\s+\\s+\\s+\\s+\\s+5\\s+";
String delimi = "\\s+\\s+\\s+\\s+\\s+6\\s+";
String delimj = "\\s+\\s+\\s+\\s+\\s+7\\s+";
String delimk = "\\s+\\s+\\s+\\s+\\s+8\\s+";
String deliml = "\\s+\\s+\\s+\\s+\\s+9\\s+";
String delimm = "\\s+\\s+\\s+\\s+\\s+a\\s+";
String delimn = "\\s+\\s+\\s+\\s+\\s+b\\s+";
String delimo = "\\s+\\s+\\s+\\s+\\s+c\\s+";
String delimp = "\\s+\\s+\\s+\\s+\\s+d\\s+";
String delimq = "\\s+\\s+\\s+\\s+\\s+e\\s+";
String delimr = "\\s+\\s+\\s+\\s+\\s+f\\s+";
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
lines.add(scanner.nextLine());}
for(int i=0; i<lines.size(); i++){
for(String s=null; i<lines.size(); i++){
s = lines.get(i);
if(!s.contains(delima)||
!s.contains(delimb)||
!s.contains(delimc)||
!s.contains(delimd)||
!s.contains(delime)||
!s.contains(delimf)||
!s.contains(delimg)||
!s.contains(delimh)||
!s.contains(delimi)||
!s.contains(delimj)||
!s.contains(delimk)||
!s.contains(deliml)||
!s.contains(delimm)||
!s.contains(delimn)||
!s.contains(delimo)||
!s.contains(delimp)||
!s.contains(delimq)||
!s.contains(delimr))
System.out.print("\r\n" + s);
else if(s.contains(delima)||
s.contains(delimb)||
s.contains(delimc)||
s.contains(delimd)||
s.contains(delime)||
s.contains(delimf)||
s.contains(delimg)||
s.contains(delimh)||
s.contains(delimi)||
s.contains(delimj)||
s.contains(delimk)||
s.contains(deliml)||
s.contains(delimm)||
s.contains(delimn)||
s.contains(delimo)||
s.contains(delimp)||
s.contains(delimq)||
s.contains(delimr))
System.out.print(s);}
}
}catch (FileNotFoundException e) {
System.out.println("Cannot find file.");
}
}
}
我的文本文件的内容是:
first line
text & append this line
所以基本上,我知道我的文本文件中包含这些字符串之一(在本例中为 delima)。然而,我的输出是:
first line
text & append this line
这是不应该发生的。我想要的输出是:
first line text & append this line
有谁知道为什么它将我的文本文件的第二行解释为好像它不包含 delima,即使它显然包含?任何帮助,将不胜感激。我相当确定问题与我的 if 语句有关,但我显然不是这里的专家。