从文本文件填充多维数组
我有一个包含用户信息的文本文件,以行形式用逗号分隔。我结合了实验和研究来尝试将每一行分成单独的信息(通过使用 split 函数),这些信息可以存储在数组中,然后进行搜索。使用代码,我将文本文件中的每个名称和用户名重复 4 次,我不明白。我所做的只是让自己更加困惑,但我需要的只是从文本文件中提取每一行,将其分成 4 个独立的信息片段,并以某种方式将它们存储在内存中以供搜索。我的代码是;
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());
}
}
}
感谢您对此的任何建议
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 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看一下代码的分解,问题就变得清晰了:
您的代码基本上是在
items
列表上迭代两次。请记住,在 Java 中,以下两个代码片段是等效的——因为它们都迭代数组或集合的值。A
B
Take a look at the break-down of your code and the problem becomes clear:
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
B