我有一个文本文件:
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/