gpt4 book ai didi

java - 无法在 Java 上输入所需的名称

转载 作者:行者123 更新时间:2023-11-29 05:35:06 26 4
gpt4 key购买 nike

我有一个文本文件:

Filename: apple.jpg
Name: Apple
Brief: Apple is a fruit

Filename: orange.jpg
Name: Orange
Brief: Orange is also a fruit

Filename: tomato.jpg
Name: Tomato
Brief: Tomato is not a fruit, it's a vegetable

我有一个代码:

public class Test
{
public static void main(String[] args) throws IOException{
Scanner reader = new Scanner(new File("C:/textLocation.txt"));

String filename = "";
String name = "";
String brief = "";

String line = "";
while (reader.hasNextLine()){
line = reader.nextLine();

if (line.startsWith("Filename:") && (line.contains("apple"))){
filename = line.substring(10, line.length());
} else if (line.startsWith("Name:")){
name = line.substring(6, line.length());
} else if (line.startsWith("Brief:")){
brief = line.substring(7, line.length());
}
}
System.out.println(filename);
System.out.println(name);
System.out.println(brief);
}
}

我遇到的问题是当我设置 apple 时,它​​使 Filename 为 apple.jpg,这是正确的,但 Name 和 Brief 是番茄的。我该如何纠正这个问题?提前谢谢你。

最佳答案

public class Test {
public static void main(String[] args) throws IOException{
Scanner reader = new Scanner(new File("C:/textLocation.txt"));

String filename = "";
String name = "";
String brief = "";
boolean lookingForName = false;
boolean lookingForBrief = false;

String line = "";
while (reader.hasNextLine()){
line = reader.nextLine();

if (line.startsWith("Filename:") && (line.contains("apple"))){
filename = line.substring(10, line.length());
lookingForName = true;
lookingForBrief = true;
} else if (line.startsWith("Name:") && lookingForName){
name = line.substring(6, line.length());
lookingForName = false;
} else if (line.startsWith("Brief:") && lookingForBrief){
brief = line.substring(7, line.length());
lookingForBrief = false;
}
}
System.out.println(filename);
System.out.println(name);
System.out.println(brief);
}

}

关于java - 无法在 Java 上输入所需的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19803297/

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