Java 扫描文件,打印所有错误,如果在文件打印中未发现错误;“什么也没找到”;一旦
如果在文件中找不到关键字“ERROR”,则打印一次“Nothing found”,此代码扫描每一行并打印每一行的输出。但如果在多行中找到“ERROR”,则需要打印所有“ERROR found” 任何帮助都将不胜感激Java 扫描文件,打印所有错误,如果在文件打印中未发现错误;“什么也没找到”;一旦,java,Java,如果在文件中找不到关键字“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(Str
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");
}
}
}
}
您希望有一个标志bool foundError,该标志被初始化为false,当您发现错误时,将其设置为true,在文件扫描结束时检查变量-如果为false,则打印“未找到任何内容”消息。据我所见,此代码将遍历文件并打印:
"Failed" + " " + nextLine
每次:
nextLine.contains("ERROR")
太好了!问题就在这里:
else if(nextLine.contains("Failed!")){
System.out.println("Not Found");
}
在每次循环中,您将检查nextLine是否包含字符串“Failed!,然后打印“未找到”
我认为你不想那样
试试这个:
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");
}
}
}
我已经纠正了if(!ifError)、print“Nothing found”(未找到)的含义,并改进了您的类名。您可能还想重新检查关于“在其原始代码中每次都找不到”的逻辑,并编辑您的帖子。如果您这样做,可能值+1。我是说他的原始代码不会每次都打印“Not found”(未找到)。
nextLine.contains(“失败!)
检查输入,而不是输出。但是如果你编辑你的帖子,它可能值+1。啊,我明白了!谢谢你提出这个问题。我会尽快编辑它。