gpt4 book ai didi

java - 使用 line.contains() 查找与特定关键字数组匹配的特定行

转载 作者:行者123 更新时间:2023-12-01 14:04:45 26 4
gpt4 key购买 nike

我有一些问题。在这里,我想在 line.contains() 中使用 string[] ,之前我尝试了一个代码,如果我放入 line.contains(String) ,它会读取关键字,但我一次只能输入一个关键字。因此,我尝试将关键字分组到一个数组中,但主要问题是 line.contains() 无法读取 String[]。

这是代码:-

package components;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class matchWord {

public static void main(String[] args) {
File file = new File("file.txt");
String[] errorType = {"uuid=A5H50AV_promo1, for domain=null", "Start node"};
Scanner scanner = null;
try {
scanner = new Scanner(file);
} catch (FileNotFoundException ex) {
System.out.println("File not found");
}

int count = 0;
//now read the file line by line
for (int i = 0; i < errorType.length; i++) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
//it doesn't read the errorType[i] as i can see that the count=0
if (line.contains(errorType[i])) {
count++;
if (count == 1) {
System.out.println("Error Description :" + line);
}
}
}
}

System.out.println("Error Type : " + errorType + "\nCount : " + count);
scanner.close();
}
}

请大家帮忙,非常感谢。

最佳答案

交换 for 和 while 循环:

   //now read the file line by line
while (scanner.hasNextLine()) {
String line = scanner.nextLine(); //also be sure to put this outside the for loop
for (int i = 0; i < errorType.length; i++) {
if (line.contains(errorType[i])) {
count++;
if (count == 1) { //also this
System.out.println("Error Description :" + line);
}
}
}
}

问题在于外部循环正在迭代错误消息以进行检查,而内部循环正在迭代文件的行。

因此,在第一个循环中,程序将根据数组中的第一个元素检查文件中的所有行,一直检查到文件末尾。从下一个循环开始,扫描仪已经位于文件末尾,因此无法再读取 - 因此内部循环甚至不会执行一次...

另外,这看起来很臭:

if (line.contains(errorType[i])) {
count++;
if (count == 1) { //also this
System.out.println("Error Description :" + line);
}
}

count == 1 条件只会一次为真。仅打印第一条错误消息。如果您需要所有错误消息(因为它看起来合乎逻辑),您可能应该这样处理这部分:

if (line.contains(errorType[i])) {
count++;
System.out.println("Error number: " + count + " Error Description :" + line);
}

关于java - 使用 line.contains() 查找与特定关键字数组匹配的特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18998362/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com