如何从文件读取到数组中特定对象的列表

时间:2019-03-24 16:22:09

标签: java

我正在一个编程项目中,您应该为在线购物商店编写代码,我有两个文件,一个文件中包含产品,另一个文件中包含帐户信息,我需要阅读这两个文件并存储它们在ArrayList中以及另一个具有类型帐户的类型中,如下面在store类中所示,我还想检查登录信息是否匹配

我已经尝试将两个文件都读取到list1和list2(它们是String类型的数组列表),并且完全可以正常工作,但是当我到达要检查用户名和密码是否有效的地步时,我尝试了以下:

    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");

但是它不能在所有情况下都起作用,并且有一些错误,所以我的老师告诉我要将文件读入产品和帐户的现有阵列列表中,但是我没有找到合适的方法... < / p>

这是帐户文件包含的示例:

0001,Salam,1234,AbdulSalam Ahmad,1223 Sultanah - Medina,05555343535,salam@hotmail.com
0002,Rawan,1111,Rawan Khaled,1223 Alaziziah - Medina,05555343435,rawan@hotmail.com

//主要:

     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;
}

}

//products class:

class Products{
 private int productID;
 private String name;
 private String supplier;
 private double price;

 public Products(){

 }
public Products(int productID,String name,String supplier, double price){
    this.productID=productID;
    this.name=name;
    this.supplier=supplier;
    this.price=price;
}
public void setProductID(int ID){
    productID=ID;
}
public void setName(String newName){
    name=newName;
}
public void setSupplier(String newSupplier){
    supplier=newSupplier;
}
public void setPrice(double newPrice){
    price=newPrice;
}
public int getID(){
    return productID;
}
public String getSupplier(){
    return supplier;
}
public String getNAme(){
    return name;
}
public double getPrice(){
    return price;
}
public String toString(){
    return" Product ID: "+productID+"\n -Product Name: "+name+"\n -Product Supplier: "+supplier+
            "\n -Product Price: "+price+"\n ******************************************";
}

}

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

使用扫描仪从数据文件中读取文本行时,请勿使用Scanner#next()方法,除非您特别希望从文件中获取每个标记(单词)。它专门用于与Scanner#hasNext()方法一起使用时从文件中检索令牌(单词)。请将Scanner#hasNextLine()Scanner#nextLine()方法结合使用。这是一个示例:

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();
}

您会注意到,我没有将帐户列表命名为 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.
    }
}

现在,这当然是基于以下假设:在每个帐户数据行中,第一项是ID号,第二项是用户名,而第三项是密码。如果将该行拆分为一个String数组,然后将第一项(ID)驻留在数组索引0,则第二项(用户名)驻留在数组索引1,而第三项(Password)驻留在数组索引2 ,依此类推。

您还有一个名为 accountIndex (好名)的变量,但是在成功找到用户名和密码后,您为此变量提供 0 。通过这样做,您可以有效地告诉您的代码,成功的帐户实际上是帐户列表中包含的第一个帐户,而不管用户名和密码是否通过了有效性。如上例所示,您应该传递给此变量的是 i 中包含的值,因为这是通过用户名/密码有效性的Accounts List元素的真实索引值。

尚未提供其余代码,因此您可以从这里独自一人。