在阵列中存储多个输入

时间:2016-07-30 19:09:06

标签: java arrays arraylist

大家好我还在学习Java专门的数组我想要做的就是创建一个迷你数据库。我想检索一个姓名,电话号码和电子邮件地址,当我打电话给一个名字时,我希望这里显示的信息是我到目前为止所得到的:

  private static  String [][] info;
  private static String name;
  private static ArrayList<String> nArray = new ArrayList<>();
  private static ArrayList<String> pArray = new ArrayList<>();
  private static ArrayList<String> eArray = new ArrayList<>();

 public static void addCustomer()
{
       Scanner new_customer = new Scanner(System.in); 

       System.out.print("Name: ");          
       name = new_customer.nextLine(); 
       nArray.add(name);

       System.out.print("Phone Number: ");
       String phone = new_customer.nextLine();
       pArray.add(phone);


       System.out.print("E-Mail Address: ");
       String email = new_customer.nextLine(); 
       eArray.add(email);                         
}     
  public static void customerInfo()
{
  int totalCustomers = nArray.size();
  System.out.print("Current Customers : "+totalCustomers+" Total\n"); 
  StringBuilder arrayOutput = new StringBuilder();
  for ( String name  : nArray) {
          arrayOutput.append(name+"\n");
  }  
    String text = arrayOutput.toString();
    System.out.print(text); 
 }
}

3 个答案:

答案 0 :(得分:1)

您可以使用此方法,首先为Customer创建一个bean类,如下所示:

public class Customer {
    private String name;
    private String phone;
    private String email;

    public Customer(String name, String phone, String email) {
        this.name = name;
        this.phone = phone;
        this.email = email;
    }
    // getters and setters
}

现在你可以像这样使用它:

// declare list for customers
List<Customer> customers = new ArrayList<>();

// get the information from the user input
....

// create Customer
Customer customer = new Customer(name, phone, email);

// add the Customer to the list
customers.add(customer);

现在您无需为保存数据声明三个不同的lists

答案 1 :(得分:1)

如果你想要做的是能够根据他们的名字显示特定的客户信息,那么你可以通过循环nArray并比较价值来实现这一目的。

public static int getCustomerIndex(String name){
    for (int q = 0; q < nArray.size(); q++){
        if (name.equals(nArray.get(q))){
            return q;
        }
    }
    return -1;
}

public static void displayCustomer(int index){
    System.out.println("Name: " + nArray.get(index));
    System.out.println("Phone #: " + pArray.get(index));
    System.out.println("Email: " + eArray.get(index));
}

你真的可能想要上课Customer,而不是有3个不同的ArrayList

答案 2 :(得分:0)

您应该对接口进行编程并确保数据的安全性。 您应该封装哪些更改。您不希望传递引用,这可能会导致更改用户信息(这是不需要的)。这可能会导致数小时的调试。大多数领域的Getter和Setter方法都违背了OO设计的目的,描述here。不是说你做过或做过,而是作为参考所有正在阅读和感兴趣的人。

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package stackexchange;

import stackexchange.user.*;

import java.util.Set;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeSet;
import java.util.TreeMap;

/**
 *
 * @author Tony
 */
public class StackExchange {
    private static Set<Customer> dataset;
    private static Map<String, Customer> emailQuery = null;
    /**
     * @param args the command line arguments
     */
    @SuppressWarnings("empty-statement")
    public static void main(String[] args) {
        Scanner istream = new Scanner(System.in);
        String in;

        dataset = new TreeSet<>(Customer.comparator);

        while (fillDatabase());

        printAll();

        while (true){
            System.out.print("Find User (y/n): ");
            in = istream.nextLine();

            // If enter null break
            if ("n".equals(in.toLowerCase()))
                break;

            System.out.print("Enter user Email: ");
            in = istream.nextLine();
            printData(findByEmail(in));
        }

    }

    /**
     * 
     * @return 
     */
    private static boolean fillDatabase(){
        Customer customer = new Customer();
        UserInfo userInfo;
        String add;
        String first;
        String last;
        String phone;
        String email;

        Scanner new_customer = new Scanner(System.in); 

        System.out.print("add user (y/n): ");          
        add = new_customer.nextLine(); 

        if ("y".equals(add.toLowerCase())){
            System.out.print("First Name: ");          
            first = new_customer.nextLine(); 

            System.out.print("Last Name: ");          
            last = new_customer.nextLine(); 

            System.out.print("Phone Number: ");
            phone = new_customer.nextLine();


            System.out.print("E-Mail Address: ");
            email = new_customer.nextLine(); 

            userInfo = new UserInfo(first, last, email, phone);
            customer.setUserInfo(userInfo);
            if (dataset.add(customer) == false){
                System.out.println("Customer : <" + first + " " + last + "> : already exists!");
            }
            return (true);
        }
        return (false);
    }

    /**
     * Get customer by id
     * @param _id [in] customer
     * @return 
     */
    private static Customer findByEmail(String _email){
        if (emailQuery == null){
            UserInfo userInfo;
            emailQuery = new TreeMap<>(); 

            for (Customer c : dataset){
                userInfo = c.getUserInfo();
                emailQuery.put(userInfo.email, c);
            }
        }

        return (emailQuery.get(_email));
    }

    /**
     * Print all data 
     */
    private static void printAll(){
        UserInfo userInfo;

        for (Customer c : dataset){
            printData(c);
        }
    }

    /**
     * Print data
     * @param _c [in] customer
     */
    private static void printData(Customer _c){
        if (_c != null){
            UserInfo userInfo = _c.getUserInfo();
            System.out.println("+==================================================+");
            System.out.println("Name: " + userInfo.firstName + " " + userInfo.lastName);
            System.out.println("Email: " + userInfo.email);
            System.out.println("Phone#: " + userInfo.phoneNumber);
            System.out.println("+==================================================+");
        }else{
            System.out.println("Error : customer cannot be null!");
        }
    }
}


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package stackexchange.user;

/**
 * Basic user information
 * @author Tony
 */
public class UserInfo {
    public final String firstName;
    public final String lastName;
    public final String email;
    public final String phoneNumber;

    public UserInfo(String _strFirstName, String _strLastName, String _strEmail,
                String _strPhoneNumber){
        firstName   = _strFirstName;
        lastName    = _strLastName;
        email       =  _strEmail;
        phoneNumber = _strPhoneNumber;
    }

}



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package stackexchange.user;

/**
 *
 * @author Tony
 */
public interface User {
    public static final int PRIVILEGE_ADMIN    = 0x00000001;
    public static final int PRIVILEGE_NORMAL   = 0x00000002;
    public static final int PRIVILEGE_GUEST    = 0x00000004;
    public static final int PRIVILEGE_UNKNOWN  = 0x80000000;

    /**
     * Getter Methods 
     */

    /**
     * User privileges 
     * @return 
     */
    int getPrivilege();

    /**
     * Object id 
     * @return id associated with this object 
     */
    String getObjectId();

    /**
     * User information (immutable)
     * @return instance of UserInfo 
     */
    UserInfo getUserInfo();

    /**
     * Setter Methods
     */

    /**
     * Set user information
     * @param _userInfo 
     */
    void setUserInfo(UserInfo _userInfo);

}


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package stackexchange.user;

import java.util.Comparator;

/**
 *
 * @author Tony
 */
public class Customer implements User{
       private final String objectId;
       private final int privilegeValue;
       private String firstName;
       private String lastName;
       private String phoneNumber;
       private String email;

    public Customer(){
        objectId = this.hashCode() + "";           // Create Unique Id for each object
        privilegeValue = User.PRIVILEGE_NORMAL;    // user privileges
    }

    @Override
    public int getPrivilege() {
        return (privilegeValue);
    }

    @Override
    public String getObjectId() {
        return (objectId);
    }

    @Override
    public UserInfo getUserInfo() {
        UserInfo userInfo = new UserInfo(firstName, lastName, email, phoneNumber);
        return (userInfo);
    }

    @Override
    public void setUserInfo(UserInfo _userInfo) {
        if (_userInfo == null){
            System.out.println("Error : argument passed cannot be null!");
        }else{
            firstName   = _userInfo.firstName;
            lastName    = _userInfo.lastName;
            email       = _userInfo.email;
            phoneNumber = _userInfo.phoneNumber;
        }
    }

    /**
     * Compare two users
     * @param _anotherCustomer [in] user to compare with
     * @return comparison result
     */
    public int compareTo(Customer _anotherCustomer){
        return (this.objectId.compareTo(_anotherCustomer.getObjectId()));
    }

    /**
     * Used for sorting information in ADT's
     */
    public static final Comparator<Customer> comparator = new Comparator<Customer>(){
        @Override
         public int compare(Customer _c1, Customer _c2){
             return (_c1.compareTo(_c2));
         }
    };
}