简体   繁体   English

将用户创建的对象存储在arrayList中多次迭代

[英]Storing user created objects in arrayList multiple iterations

I have searched the internet for an answer to the problem that I am having and cannot seem to get the answer that I am looking for, I have two classes and application class and a users class, I am prompting the user to enter either a new user or return the results of the users already in an array list that is set up to hold users objects. 我已经在互联网上搜索了我遇到的问题的答案,但似乎无法获得我正在寻找的答案,我有两个类,应用程序类和一个用户类,我在提示用户输入新的用户或返回用户的结果(已设置为保留用户对象的数组列表中)。 After the application ends, I expect the array list to continue to house the objects so that with each successive run of the main method in the application class I can refer to the arrayList for cross checking later on. 应用程序结束后,我希望数组列表继续容纳对象,以便在应用程序类中每次连续运行main方法时,我都可以引用arrayList稍后进行交叉检查。

So my question is, When the main method is completed and I run it again, does it re-create all my objects and arrayList starting from scratch? 所以我的问题是,当main方法完成并再次运行时,它是否从头开始重新创建我的所有对象和arrayList?

Below are my two classes that I am working with. 以下是我正在使用的两个课程。 Application class first, and Users second. 首先是应用程序类,然后是用户。

import java.util.ArrayList;
import java.util.Scanner;

public class Application{
    static Scanner in = new Scanner(System.in);


    public static void main(String[] args) {


    //Creating admin user object that will be able to access everything
        Users admin = new Users();
        Users result = null;


    //creating a new user that is not an admin
        System.out.println("Are you a new user?");
        String answer = null;
        answer = in.nextLine();

        if(answer.equalsIgnoreCase("YES") || answer.equalsIgnoreCase("Y")) {
            result = admin.addNewUser();
            result.addUsertoArrayList(result);
        }else {
            result.displayUsers(result.users);
        }
    }//End of Main Method.
}//End of Application Class

import java.util.ArrayList;

public class Users extends Application {

    private String username;
    private double biWeeklyIncome = 0;
    private String password;
    private String email;

// ArrayList to store all the objects of Type Users.
    ArrayList<Users> users = new ArrayList<Users>();



// Default Constructor.
    Users() {
    }

// Constructor that takes a string as a name parameter.
    public String name;

    Users(String name) {
        this.name = name;
    }

// Setter Methods.

// User name
    public void setUsername() {
        System.out.println("Enter the username that you wish to go by:\n Ex.      bigBoss45");
       username = in.nextLine();
    }

// Income
    public void setBiWeeklyIncome() {
        System.out.println("Enter your current bi-weekly income: \n Ex.   4500.00");

        try {
            biWeeklyIncome = Double.parseDouble(in.nextLine());
        } catch (NumberFormatException e) {
        // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

// Password
    public void setPassword() {
        System.out.println("Enter the password that you wish to access your account with:\n Ex. bigBoss45");


        password = in.nextLine();
    }

// Email
    public void setEmail() {
        System.out.println("Enter a valid email address: \n Ex. bigBoss45@gmail.com");

        email = in.nextLine();
    }

// Getter Methods

// User name
    public String getUsername() {
        return username;
    }

// Income
    public double getBiWeeklyIncome() {
        return biWeeklyIncome;
    }

// Password
    public String getPassword() {
        return password;
    }

// Email
    public String getEmail() {
        return email;
    }

// Method to create a new user
    public Users addNewUser() {
        String name = null;

        System.out.println("Enter the name of the new user\n Ex.John Smith");
        name = in.nextLine();
    // Creating the new
        Users newUser = new Users(name);

    // Setting the new users information
        newUser.setUsername();
        newUser.setPassword();
        newUser.setBiWeeklyIncome();
        newUser.setEmail();

    //adding the new user to the users arrayList

        displayUsers(users);

        return newUser;
}// end of addNewUser method.

//Method that is going to add a new user to the array List.
    public void addUsertoArrayList(Users nUser) {
        users.add(nUser);
    }

    public void displayUsers(ArrayList<Users> users) {
    // Printing out the user added to the array list for testing purposes.
        for (Users user : users) {
            System.out.println(user.getUsername());
        }
    }//End of displayUser method.


}

I am kind of new to Java and all the object orientation's so any help is much appreciated and I thank you for taking the time to look at my code! 我是Java和所有面向对象的新手,因此非常感谢您的帮助,也感谢您抽出宝贵的时间来查看我的代码!

Every time you run a command like java Application to run the program you will be starting up a new java process. 每次您运行诸如java Application类的命令来运行该程序时,您都将启动一个新的java进程。 No data from memory will be carried over from any previous executions of your java program. Java程序的任何先前执行都不会继承内存中的数据。

If you want to store data so that it stays the same over multiple executions of your process you should consider externalising it to a file or a DB etc. 如果要存储数据,以便在多次执行过程中数据保持不变,则应考虑将其外部化为文件或数据库等。

When the application is shut down, the objects stored in memory are lost. 当应用程序关闭时,存储在内存中的对象将丢失。

You can choose to persist desired objects. 您可以选择保留所需的对象。 One way to do this is to serialize objects to a file before shutdown, then reload them on startup. 一种方法是在关机之前将对象序列化为文件,然后在启动时重新加载它们。

In your case, an easy way to do this would be to use Java serialization . 就您而言,一种简单的方法是使用Java序列化 You'll need to mark your serializable classes as implementing Serializable , give them a serialVersionUID field, and use ObjectOutputStream and ObjectInputStream . 您需要将可序列化的类标记为实现Serializable ,为它们提供一个serialVersionUID字段,并使用ObjectOutputStreamObjectInputStream

By the way, your Users class represents two different things - a collection of users and a single user. 顺便说一句,您的Users类代表两种不同的事物-一个用户集合和一个用户。 Usually things will work better if each class represents one concept. 通常,如果每个类代表一个概念,那么事情会更好。 Consider splitting your Users class into two classes, one of which holds a list of users, and the other representing a single user. 考虑将您的Users类划分为两个类,其中一个包含一个用户列表,另一个代表一个用户。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM