gpt4 book ai didi

java - 如何从文本文件存储到数组行标记中?

转载 作者:行者123 更新时间:2023-11-30 11:38:02 25 4
gpt4 key购买 nike

我有一个包含以下内容的文本文件:

First Name : Javier Last Name : Smith E-mail : smith@.com Password: jsmith Date of Birth: Jan 1, 1987

First Name : Jade Last Name : Tux E-mail : nicholson@.com Password: jade123 Date of Birth: Jan 1, 1954

First Name : Bruce Last Name : Porto E-mail : bruce_porto@.com Password: br11 Date of Birth: Feb 25, 1946

我想在第一行获取字符串 Javier、Smith、smith@.com、jsmith 等等,并将这些字符串存储在类型为 person (string, tring, string, string) 的数组列表中,然后执行相同的操作每行。

到目前为止,这是我的代码:

try
{
searchUser = new Scanner(new FileInputStream("src/users.txt")).useDelimiter(":");
String storeFirst = "", storeLast = "", storeEmail = "", storePassword = "";
usersArray = new ArrayList<Person>();
String line = null;

while(searchUser.hasNextLine())
{
line = searchUser.nextLine();
storeFirst = searchUser.next();
storeLast = searchUser.next();
storeEmail = searchUser.next();
storePassword = searchUser.next();
line = searchUser.nextLine();

usersArray.add(new Person(storeFirst, storeLast, storeEmail, storePassword));

for(Person ae : usersArray)
{
System.out.println(ae.toString());
}
System.out.println(storeFirst);
System.out.println(storeLast);
System.out.println(storeEmail);
System.out.println(storePassword);

}
searchUser.close();
}

最佳答案

将您的 while 循环更改为首先读取并填充数组,然后在外部打印循环:

 while(searchUser.hasNextLine()){
//read the tokens first ignoring tag tokens
searchUser.next();//ignore "First Name"
storeFirst = searchUser.next().split(" ")[0];//split the 3 words and take 1st
storeLast = searchUser.next().split(" ")[0];//split the 2 words and take 1st
storeEmail = searchUser.next().split(" ")[0];//split the 2 words and take 1st
storePassword = searchUser.next().split(" ")[0];//split the 2 words and take 1st
//read and ignore remaining text including the new line character in the end
searchUser.nextLine();

Person person = new Person(storeFirst, storeLast, storeEmail, storePassword);
usersArray.add(person);
}

现在打印代码为:

 for(Person ae : usersArray){
System.out.println(ae.toString());
}

关于java - 如何从文本文件存储到数组行标记中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13785328/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com