Populating multidimensional array from textfile
I have a textfile containing users' information, in row form separated with commas. I've used a combination of experimenting and research to try and separate each row into individual pieces of information (by using the split function) which can be stored in the array, and then searched against. With the code I have each name and username in the textfile gets repeated 4 times each, how I don't understand. All i've managed to do is confuse myself further, but all I need 开发者_JAVA技巧is to pull each row from the textfile, split it into its 4 separate pieces of information and store them in memory in some way to search against. The code i have is;
package assignment;
import java.io.*;
public class readUser {
public void read()
{
try{
FileInputStream propertyFile = new FileInputStream("AddUser.txt");
DataInputStream input = new DataInputStream(propertyFile);
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = reader.readLine()) != null) {
String[] items = line.split(",");
String[][] usersArray = new String [5][2];
int i;
for (String item : items) {
for (i = 0; i<items.length; i++){
if (i == 0) {
System.out.println("Name: " + items[i]);
} else if (i == 1) {
System.out.println("Username: " + items[i]);
}
}
}
//System.out.println(line);
}
input.close();
}
catch (Exception e){
System.err.println("Error: " + e.getMessage());
}
}
}
Thanks for any advice on this
Take a look at the break-down of your code and the problem becomes clear:
for each line in property file (while loop):
for each item in line:
for each item in line:
if item 0 print username
else if item 1 print username
endif
end loop
end loop
end loop
Your code is basically iterating over the list of items
twice. Keep in mind that in Java the following two code snippets are equivalent -- in that they both iterate over the values of an array or collection.
A
for (String item : items) {...}
B
for (int i = 0; i < items.length; i++) {
String item = items[i];
....
}
精彩评论