Java – save values in a loop
•
Java
I'm trying to read the value of my country array string, which reads CSV files
InputStreamReader reader = new InputStreamReader(asset_stream);
br = new BufferedReader(reader);
String[] country = null;
String cvsSplitBy = ";";
try {
while ((line = br.readLine()) != null) {
country = line.split(cvsSplitBy);
}
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
My code is currently storing the value in the country variable But when my loop ends, I only read the last value in the loop How do I store all the values so that I can print them after the loop is completed?
Solution
Consider using a list to save values:
List<String[]> countries = new ArrayList<>();
try {
while ((line = br.readLine()) != null) {
countries.add(line.split(cvsSplitBy));
}
}
You can traverse this list later:
for (String[] country : countries) {
System.out.println(Arrays.toString(country); // or whatever
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
