There are quite a few things to note about your code:
- you probably miss
{}
after the if
-statement and therefore update name every run of the while
-loop
- you access
[1]
without checking how many elements the split("=")
yielded
- you literally call
split("=")
4 times on almost every line. Save CPU-time by introducing a temporary variable!
- you can replace your
while
-loop by a for
-loop which also finds name=value
in the first line and does not "throw up" if name=value
is not inside any of the lines (you don't check whether i
is less than lines.length
)
I left your comments inside my answer; feel free to remove them.
Variant a (using an index):
for (int i = 0; i < lines.length; i++) {
// Only split once and keep X=Y together in name=X=Y by specifying , 2
final String[] split = lines[i].split("=", 2);
if (split.length == 2 && split[0].equals("name")){ // If the field is name...
System.out.println(split[1]); // Prints the value of the field
name = split[1]; // <-- My problem is here
break; // no need to look any further
}
}
Variant b (using "for-each"):
for (String line : lines) {
// Only split once and keep X=Y together in name=X=Y by specifying , 2
final String[] split = line.split("=", 2);
if (split.length == 2 && split[0].equals("name")) { // If the field is name...
System.out.println(split[1]); // Prints the value of the field
name = split[1]; // <-- My problem is here
break; // no need to look any further
}
}