如果在文件中找不到关键字“ERROR”,则打印“Nothing Found”一次,此代码扫描每一行并打印每行的输出。但如果在多行中找到“ERROR”,则需要打印所有“ERROR found。
任何帮助将不胜感激!
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Scan {
public static void main(String[] args) throws FileNotFoundException {
Scanner s = new Scanner(new File("Users/home/test.txt"));
while(s.hasNextLine()){
//read the file line by line
String nextLine = s.nextLine();
//check if the next line contains the key word
if(nextLine.contains("ERROR"))
{
//whatever you want to do when the keyword is found in the file
System.out.println("Failed" + " " + nextLine);
}
else if(nextLine.contains("Failed!")){
System.out.println("Not Found");
}
}
}
}
答案 0 :(得分:2)
从我看到的,这段代码将遍历文件并打印:
"Failed" + " " + nextLine
每次:
nextLine.contains("ERROR")
太棒了!问题出在这里:
else if(nextLine.contains("Failed!")){
System.out.println("Not Found");
}
在每个循环中你将检查nextLine是否包含字符串“Failed!”,然后打印“Not Found”。
我不认为你想要那个。
试试这个:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ErrorScanner
{
public static void main(String[] args) throws FileNotFoundException
{
Scanner s = new Scanner(new File("Users/home/test.txt"));
boolean ifError = false;
while(s.hasNextLine())
{
String nextLine = s.nextLine();
if(nextLine.contains("ERROR"))
{
System.out.println("Failed" + " " + nextLine);
ifError = true;
}
}
if(! ifError)
{
System.out.println("Nothing found");
}
}
}
答案 1 :(得分:1)
你想要一个标志bool foundError初始化为false,当你发现错误设置为true时,在文件扫描结束时检查变量 - 如果是false则打印你的“找不到”消息