I have an alternative solution that is different that use a loop. My idea is to have a method that checks if the index exists and return the value of this index, if not exist I can provide a default value.
Class
public class Main {
public static void main(String[] args) {
String[] fields = "2,2,2,2,2,2,".split(",");
int seats = Integer.parseInt(getValue(fields, 5, "0"));
int cabincrewrequired = Integer.parseInt(getValue(fields, 6, "0"));
System.out.println(seats);
System.out.println(cabincrewrequired);
}
private static String getValue(String[] fields, int index, String defaultValue) {
return fields.length > index ? fields[index] : defaultValue;
}
}
Output
2
0
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…