Let's say that we have a this text file with animals and their color:
dog=brown
cat=yellow
bird=red
I need to get the color of the animal, so i wrote this method. I call the method with the animal i want the color of in the parameter.
public String getAnimal(String animal) throws IOException{
Scanner sc = new Scanner(TEXT_FILE).useDelimiter("=");
for (int i = 0; i < 3; i++){
if(sc.nextLine().startsWith(animal)){
sc.next();
return sc.next();
}
sc.nextLine();
}
return null;
}
It only semi works. For example calling System.out.println(getAnimal("cat"));
, prints:
yellow
cat
It's like if the scanner ignored the fact that there are any lines and prints anything between the delimiters.