Java 如何将文件读入特定对象的数组列表
我正在进行一个编程项目,假设您为一个在线购物商店编写一个代码,我有两个文件,一个包含产品,另一个包含帐户信息,我需要读取这两个文件并将其存储在ArrayList中,另一个包含类型accounts,,的文件,如下所示,在store类中,我还要检查登录信息是否匹配 我已经尝试将这两个文件读取到list1和list2(这是字符串类型的数组列表),效果非常好,但当我要检查用户名和密码是否有效时,我尝试了以下操作:Java 如何将文件读入特定对象的数组列表,java,Java,我正在进行一个编程项目,假设您为一个在线购物商店编写一个代码,我有两个文件,一个包含产品,另一个包含帐户信息,我需要读取这两个文件并将其存储在ArrayList中,另一个包含类型accounts,,的文件,如下所示,在store类中,我还要检查登录信息是否匹配 我已经尝试将这两个文件读取到list1和list2(这是字符串类型的数组列表),效果非常好,但当我要检查用户名和密码是否有效时,我尝试了以下操作: int accountIndex=-1; for (int i = 0;
int accountIndex=-1;
for (int i = 0; i < list2.size(); i++) {
if((list2.get(i).contains(username))&& (list2.get(i).contains(password))){
accountIndex=0;
}
}
if(accountIndex<0)
System.out.println("Login Failed! Invalid Username and/or Password.\n");
//主要内容:
public static void main(String[] args) throws FileNotFoundException {
int ans;
// Craete a Store object
Store store = new Store("Camera Online Store");
// Read all products from the products file
ArrayList<String>list1=new ArrayList<String>();
File products = new File("Products.txt");
try(Scanner input = new Scanner(products);)
{
input.useDelimiter(",");
while(input.hasNext()){
list1.add(input.nextLine());
}
input.close();
}
// Read all accounts from the account file
File customerFile = new File("Accounts.txt");
ArrayList<String>list2=new ArrayList<String>();
try(Scanner input = new Scanner(customerFile);)
{
input.useDelimiter(",");
while(input.hasNext()){
list2.add(input.nextLine());
} input.close();
}
System.out.println("^^^^^^ Welcome to our "+store.getName()+" ^^^^^");
System.out.println("*****************************************");
while(true)
{
System.out.println("Are you a customer or an admin?\n (1) for user \n (2) for admin\n (3) to exit");
Scanner sc = new Scanner (System.in);
int choice = sc.nextInt();
switch (choice) {
case 1: // customer mode
System.out.println("Enter your login information.");
System.out.print("Username:");
String username = sc.next();
System.out.print("Password:");
String password = sc.next();
int accountIndex=-1;
for (int i = 0; i < list2.size(); i++) {
if((list2.get(i).contains(username))&& (list2.get(i).contains(password))){
accountIndex=0;
}
}
/*
get the account index for this customer
*/
if(accountIndex<0)
System.out.println("Login Failed! Invalid Username and/or Password.\n");
else{
do
{
System.out.println("Choose the required operations from the list below:\n (1) Display all products \n (2) Add a product to your shopping cart by id \n (3) View the products in your shopping cart \n (4) Go to checkout\n (5) Go back to main menu");
//Store class:
class Store{
private String name;
private ArrayList<Account> arracc;
private ArrayList<Products> arrprod;
public Store(){
}
public void setArrAcc(Account x){
arracc.add(x);
}
public void setArrProd(Products x){
arrprod.add(x);
}
public Store(String name){
this.name=name;
}
public void addProduct(Products p){
arrprod.add(p);
}
public void deleteProduct(int id){
arrprod.remove(id);//id is the product index
}
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
}
任何帮助都将不胜感激 使用扫描器从数据文件中读取成行文本时,除非您特别想要文件中的每个标记(单词),否则不要使用该方法。它是专门为在与方法一起使用时从文件中检索标记(单词)而设计的。请改为与该方法结合使用。以下是一个例子:
File customerFile = new File("Accounts.txt");
ArrayList<String> accountsList = new ArrayList<>();
// Try With Resources...
try (Scanner input = new Scanner(customerFile)) {
while (input.hasNextLine()) {
String line = input.nextLine().trim(); // Trim each line as they are read.
if (line.equals("")) { continue; } // Make sure a data line is not blank.
accountsList.add(line); // Add the data line to Account List
}
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
File customerFile=新文件(“Accounts.txt”);
ArrayList accountsList=新的ArrayList();
//尝试使用资源。。。
尝试(扫描仪输入=新扫描仪(customerFile)){
while(input.hasNextLine()){
String line=input.nextLine().trim();//在读取每一行时对其进行修剪。
如果(line.equals(“”){continue;}//请确保数据行不是空的。
accountsList.add(行);//将数据行添加到帐户列表
}
}
捕获(FileNotFoundException ex){
例如printStackTrace();
}
您会注意到,我没有将帐户列表命名为list2。虽然这是一个偏好的问题,但它只是描述得不够。我方便地将它命名为accountsList,这使得查看变量的用途更加容易
虽然您可以不受惩罚,但我不会使用contains()方法来检查用户名和密码。当帐户列表变大时,您会发现它不够准确。相反,将每个帐户行拆分为一个字符串数组,并访问用户名和密码所在的特定索引,例如:
int accountIndex = -1;
for (int i = 0; i < accountsList.size(); i++) {
// Split the current accounts data line into a String Array
String[] userData = accountsList.get(i).split(",");
// Check User Name/Password valitity.
if (userData[1].equals(username) && userData[2].equals(password)) {
accountIndex = i;
break; // Success - We found it. Stop Looking.
}
}
intaccountindex=-1;
对于(int i=0;i
现在,这当然是假设在每个帐户数据行中,第一项是ID号,第二项是用户名,第二项是密码。如果此行被拆分为一个字符串数组,那么第一个项目(ID)将驻留在数组索引0处,第二个项目(用户名)驻留在数组索引1处,第三个项目(密码)驻留在数组索引2处,依此类推
您还有一个名为accountIndex(好名字)的变量,但在成功找到用户名和密码后,您将0提供给该变量。通过这样做,您可以有效地告诉您的代码,成功的帐户实际上是帐户列表中包含的第一个帐户,而不管哪个用户名和密码已通过有效期。您应该传递给此变量的是i中包含的值,如上面的示例所示,因为这是传递用户名/密码有效性的Accounts List元素的真实索引值
您的代码的其余部分尚未提供,因此您可以从这里独立完成。在您的帖子中,您可以将帐户文件的内容显示为一个逗号分隔的长字符串。这真的是文件中数据的格式化方式吗?非常感谢!!很抱歉,我仍然是一个bigenner,我知道我应该更加注意命名我的变量!再次感谢你!
File customerFile = new File("Accounts.txt");
ArrayList<String> accountsList = new ArrayList<>();
// Try With Resources...
try (Scanner input = new Scanner(customerFile)) {
while (input.hasNextLine()) {
String line = input.nextLine().trim(); // Trim each line as they are read.
if (line.equals("")) { continue; } // Make sure a data line is not blank.
accountsList.add(line); // Add the data line to Account List
}
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
int accountIndex = -1;
for (int i = 0; i < accountsList.size(); i++) {
// Split the current accounts data line into a String Array
String[] userData = accountsList.get(i).split(",");
// Check User Name/Password valitity.
if (userData[1].equals(username) && userData[2].equals(password)) {
accountIndex = i;
break; // Success - We found it. Stop Looking.
}
}