gpt4 book ai didi

java - 使用 "patern' 和 "matcher"我怎样才能返回所有元素而不仅仅是第一个元素

转载 作者:行者123 更新时间:2023-12-01 19:43:59 27 4
gpt4 key购买 nike

我的任务是创建随机恶棍对象并写入文件。然后我创建一个类,为每个创建的恶棍创建适当的 super 英雄并将文件重写到新文件夹。我使用模式来捕获所需的统计数据和匹配器来创建具有相同统计数据的英雄对象。但是,如果恶棍对象不止一个,我的代码只会为第一个对象创建英雄......在附加的示例代码中,如果有不止一行恶棍,我如何为每个恶棍创建 super 英雄。感谢您的帮助

public class ShieldMonitoring {
private static final Pattern VILLAIN_LINE = Pattern.compile("Villain .* with superpower (.*) at level (.*)");

public static void main(String[] args) {
List<String> lines = loadFromFile();

if (lines.isEmpty()) {

} else {

System.out.println(lines.size()-1+" people saved by:");

}


SuperHero hero = findHero(lines);

if(hero != null) {

try (BufferedWriter output = new BufferedWriter(new FileWriter("Battlezone/battle-zone-1.txt", true))) {
output.write("Defeated by");
output.newLine();
output.write(hero.toString());
output.newLine();
System.out.println(hero.toString());


} catch (IOException e) {
System.out.println(e.getMessage());
}

new File("Battlezone/battle-zone-1.txt").renameTo(new File("Saved-the-world-again/battle-zone-1.txt"));

}

}

private static SuperHero findHero(List<String> lines) {
for (String line : lines) {

Matcher matcher = VILLAIN_LINE.matcher(line);
if (matcher.matches()) {
String power = matcher.group(1);
int level = Integer.valueOf(matcher.group(2));

SuperThing superThing = new SuperThing();
for(SuperHero hero : superThing.getHero()) {
if(hero.getHeroLevel() == level && hero.getSuperpower().equals(power)) {
return hero;
}
}
}

}
return null;
}

public static List<String> loadFromFile() {
try {
File VillainFile = new File("Battlezone/battle-zone-1.txt");
if (!VillainFile.exists()) {
return Collections.emptyList();
}
try (BufferedReader buffReader = new BufferedReader(new FileReader(VillainFile))) {


return buffReader.lines()
.collect(Collectors.toList());



}
} catch (Exception ex) {
System.out.println(ex.getMessage());
return Collections.emptyList();
}
}

}

最佳答案

SuperHero hero = findHero(lines);

在上面的行中,您只是为所有行/恶棍找到一个英雄。本质上,如果您需要为每一行/反派找到一个英雄,则必须修改查找并返回英雄的方法(SuperHero 对象的列表)。所以你可以将上面的行修改为:

List<SuperHero> hero = findHeroes(lines);

并类似地实现 findHeroes 方法,通过遍历各行,将英雄添加到列表中并返回英雄列表,如下所示:

private static List<SuperHero> findHeroes(List<String> lines) {
List<SuperHero> heroes = new ArrayList<SuperHero>();
for (String line : lines) {

Matcher matcher = VILLAIN_LINE.matcher(line);
if (matcher.matches()) {
String power = matcher.group(1);
int level = Integer.valueOf(matcher.group(2));

SuperThing superThing = new SuperThing();
for(SuperHero hero : superThing.getHero()) {
if(hero.getHeroLevel() == level && hero.getSuperpower().equals(power)) {
heroes.add(hero);
}
}
}

}
return heroes;
}

关于java - 使用 "patern' 和 "matcher"我怎样才能返回所有元素而不仅仅是第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59147029/

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