+ 1
In java if i want to assign an array values from a second file, how do I code that?
Let's call it String [] Names; and a method is supposed to read a file called List.names and assign each new line to a new array element. so if List.names content is Valerie Sable Wade Sherry the array should be String [] Names = {"Valerie","Sable","Wade","Sherry"} How should the code look to do this?
2 odpowiedzi
+ 2
It would be better to use a List instead of an array as an array is not dynamic. A list data type works in a similar way to an array but can have items added and removed dynamically.
List<String> names = new ArrayList<String>();
BufferedReader reader = null;
try {
File file = new File("names.txt");
reader = new FileReader(file);
String line = null;
while((line = reader.readLine()) != null) {
names.add(line);
} catch (IOException e) {
e.printStackTrace();
} finally {
reader.close();
}
To retrieve an item from the list use names.get(index);
+ 1
ok, I'll need to look into it more to understand it myself as I just started learning Java and am planning to rewrite a program I wrote in c++ win32 api.
And thank you.
Edit 3 minutes later: Irony is I just got to the part talking about ArrayList.
Edit 30 minutes later: ok just took a second look and understand most of it.