Arraylist java program - java

Help in writing a program using the array list which stores the values of name, address, phone number, date and time (for each customer) and later I need to retrieve the specific information like all the customer's name on a specified date. any help is appreciated.
Code:
public class Details {
public static void main(String args[]) throws IOException {
InputStreamReader rdr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(rdr);
String s;
s = br.readLine();
System.out.println("PLEASE ENTER CLIENT NAME");
String name = br.readLine();
System.out.println("PLEASE ENTER CLIENT ADDRESS");
String add = br.readLine();
System.out.println("PLEASE ENTER CLIENT CONTACT PHONE NUMBER");
String pnum = br.readLine();
List list = new ArrayList();
list.add("name");
list.add("add");
list.add("pnum");
list.add("food");
}
}

Create a class Customer like this -
public class Customer{
private String name;
private String address;
private String phoneNumber;
private Date date;
public Customer(name, address, phoneNumber, date){
this.name = name;
this.address = address;
this.phoneNumber = phoneNumber;
this.date = date;
}
//getters and setters method
}
After that you create an ArrayList of Customer like this -
List<Customer> `customerList` = new ArrayList<Customer>();
Now create an object/instance of Customer like this -
Customer aCustomer = new Customer("ranjit", "someAddress", "023-859 74", new Date() );
Then add the Customer object/instance aCustomer to ArrayList of Customer - customerList like this:
customerList.add(aCustomer);
In the given way you can more easily handle a Customer. Now you have a single entity containing all the customer attributes (name, address, phoneNumber etc). So you don't need store all the attributes/property in separate ArrayList

Related

How do I add to an ArrayList from one class, when the ArrayList and constructors/getters are stored 2 other classes

I have 3 classes, Session, Employee, and Employees. The Employee class has the constructors and getters, the Employees class has the ArrayList, and I'm trying to add to that ArrayList within the Session class.
public class Employee {
public Employee(String name, String email){
this.name = name;
this.email = email;
}
public String getName(){
return name;
}
public String getEmail(){
return email;
}
}
public class Employees {
private ArrayList<Employee> employees = new ArrayList<Employee>();
public Employees(){
employees.add(new Employee("John Smith", "johnsmith#email.com"));
}
public void addEmpNew (Employee empNew){
employees.add(empNew);
}
}
public class Session {
private void addEmployee(){
System.out.print("Name: ");
String addEmpName = In.nextLine();
System.out.print("Email: ");
String addEmpEmail = In.nextLine();
Employees v1 = new Employees();
v1.addEmpNew(new Employee(addEmpName, addEmpEmail));
}
}
But when I run it and put in the new employee and use a viewEmployees() method that shows all employees, It doesn't show the new one I added in, only showing the john smith one I pre-wrote in. I have a suspicion there may be something wrong with the addEmpNew method but I'm not sure.
You are creating an instance of Employees (called v1) within the addEmployee method. After the addEmployee method completes, all of the variables inside the method are gone (ready to be garbage collected).
If you are expecting to only have one instance of the Employees, consider making it a global variable.
public class Session {
private final Employees v1 = new Employees();
private void addEmployee(){
System.out.print("Name: ");
String addEmpName = In.nextLine();
System.out.print("Email: ");
String addEmpEmail = In.nextLine();
v1.addEmpNew(new Employee(addEmpName, addEmpEmail));
}
private void printEmployees(){
// you will have to implement the toString method in Employees class
System.out.print("Employees: " + v1.toString());
}
}

Why does the 'contains' method return false when I enter the exact name on my ArrayList? [duplicate]

This question already has answers here:
Java List.contains(Object with field value equal to x)
(13 answers)
Closed 1 year ago.
I am trying to make a program that can add a customer's name, age, contact number and email. And I want to search for the name that the user wants, but it does not search the name even if I entered the same name exactly. How can I fix this?
Here is my code:
package com.company;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<customers> customers = new ArrayList<>();
customers.add(new customers("Zen",19,"0912121212","zen#gmail.com"));
customers.add(new customers("Mary",20,"09134343434","mary#gmail.com"));
System.out.println("Enter name: ");
String name = scan.nextLine();
System.out.println(customers.contains(name));
}
}
class customers{
private String name;
private int age;
private String contactNumber;
private String email;
public customers(String name, int age, String contactNumber, String email) {
this.name = name;
this.age = age;
this.contactNumber = contactNumber;
this.email = email;
}
}
List.contains()uses Object.equals() to determine whether an Object is already in that List.
So one approach could be to overwrite that method:
public class Customer
{
private String m_Name;
private int m_Age;
…
#Override
public final boolean equals( final Object o )
{
return o instanceof String name && name.equals( m_Name );
}
}
Although this will work, it is not recommended to implement equals() in this way (see here as a starting point).
Instead you should search for the name in the list:
String name = scan.nextLine();
System.out.println( customers.stream().anyMatch( c -> c.getName().equals( name ) ) );
A completely different approach would be to store the Customer objects not in an instance of List but in an instance of Map, with the name as the key:
public class Main
{
public static void main( String... args )
{
Scanner scan = new Scanner(System.in);
Map<String,Customer> customers = new HashMap<>();
var customer = new Customer( "Zen", 19, "0912121212", "zen#gmail.com" );
customers.put( customer.getName(), customer );
customer = new Customer( "Mary", 20, "09134343434", "mary#gmail.com" );
customers.put( customer.getName(), customer );
System.out.println( "Enter name: " );
String name = scan.nextLine();
System.out.println( customers.containsKey( name ) );
}
}
Finally, it would help in general if you would follow the basic naming conventions for the Java language: class names are starting with a Capital letter.
name is a String. Your List contains customers instances, not Strings. Therefore your List doesn't contain name.
In order to lookup an instance of one type by a key of another type, you can use a Map:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Map<String,customers> customers = new HashMap<>();
customers.put("Zen",new customers("Zen",19,"0912121212","zen#gmail.com"));
customers.put("Mary",new customers("Mary",20,"09134343434","mary#gmail.com"));
System.out.println("Enter name: ");
String name = scan.nextLine();
System.out.println(customers.containsKey(name));
}
Or, if you want to search for a customers instance having a certain name, you can iterate over the elements of your List (either with a loop or with a Stream).
For example:
System.out.println(customers.stream().anyMatch(c -> c.getName().equals(name)));
This is assuming your customers class has a getName() getter method.
Add another constructor to your class for just name and iterate over all objects in array list for the same name.
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<customers> customers = new ArrayList<>();
customers.add(new customers("Zen",19,"0912121212","zen#gmail.com"));
customers.add(new customers("Mary",20,"09134343434","mary#gmail.com"));
System.out.println("Enter name: ");
String name = scan.nextLine();
customers obj = new customers(name);
customers toBeChecked;
for (int i=0; i<customers.size(); i++) {
toBeChecked = customers.get(i);
if(toBeChecked.getName().equals(obj.getName())) {
System.out.println("Same name");
}
}
}
}
class customers{
private String name;
private int age;
private String contactNumber;
private String email;
public customers(String name, int age, String contactNumber, String email) {
this.name = name;
this.age = age;
this.contactNumber = contactNumber;
this.email = email;
}
public customers (String name) {
this.name = name;
}
public String getName() {
return name;
}
}
The problem here is that you're not defining the ArrayList with a String type. If you want to keep the customers in your list, you can try this solution:
for(customers c:customers){
if(c.getName().equals(name)){
System.out.println(true);
}
}
Make sure to create a getter ( getName() ).

The constructor AddPatron(String, String) is undefined

I'm trying to create these commands and I get an error when creating the AddPatron
if (cmd.equals("addbook")) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Title: ");
String title = br.readLine();
System.out.print("Author: ");
String author = br.readLine();
System.out.print("Publication Year: ");
String publicationYear = br.readLine();
return new AddBook(title, author, publicationYear);
} else if (cmd.equals("addpatron")) {
BufferedReader brr = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Name: ");
String name = brr.readLine();
System.out.print("Phone: ");
String phone = brr.readLine();
return new AddPatron(name, phone);
Error: The constructor AddPatron(String, String) is undefined
It says to add constructors, however I have already done this exactly the way of AddBook. However the only difference is the AddPatron class has 2 extra Strings which I haven't included that I want to read in.
public class AddPatron implements Command {
private final String name;
private final String phone;
private final String id;
private final String list_of_books_borrowed;
public AddPatron(String name, String phone, String id, String list_of_books_borrowed){
this.name = name;
this.phone = phone;
this.id = id;
this.list_of_books_borrowed = list_of_books_borrowed;
}
}
public AddPatron(String name, String phone, String id, String list_of_books_borrowed)
This constructor requires 4 different strings.
new AddPatron(name, phone);
But here, you only pass 2 strings. You need to pass the other two or write a new constructor that only accepts the name and phone.
Note that classes represent things and their names should generally be nouns. On the other hand methods are actions and their names should be verbs. So you can have a method named addPatron() and a class named Patron. Naming a class AddPatron can be confusing.

How to create an object in java with some fields located in a driver class?

I am still pretty new with Java so don't hesitate if you think I am wildly off here...
I have a Java program with multiple object blueprint classes, a menu class, and a driver class. The driver class calls menu. In the menu class, I create a customer object while instantiating only 1 of it's 4 fields. The field is unique ID field. I want to get the other 3 fields from an ArrayList located in the driver class. How can I choose a customer object from an ArrayList in a separate class?
The first Object I am trying to create.
public class Customer {
private int id;
private String name;
private String address;
private String phone;
public static int count = 100;
public Customer(String name, String address, String phone) {
this.id = count;
this.name = name;
this.address = address;
this.phone = phone;
count++;
}
}
Reservation has a Customer
public class Reservation {
static Scanner scan = new Scanner(System.in);
private Customer customer;
private Flight flight;
private int partySize;
private double reservationCost;
final private double FIRST_CLASS_COST = 850.00;
final private double ECONOMY_COST = 450.00;
public Reservation(Customer customer, Flight flight, int partySize, double reservationCost) {
this.customer = customer;
this.flight = flight;
this.partySize = partySize;
this.reservationCost = reservationCost;
}
In the driver class, called AirlineDriver, there is an ArrayList of Customers. In the code below, how would I create a Customer object to then create a Reservation if I need to get one of the Customers in the ArrayList in the driver?
public class Menu {
static Scanner scan = new Scanner(System.in);
public Reservation createReservation() {
Customer cust = new Customer();
Flight flight;
Reservation reservation;
System.out.println("Are you a returning customer? (Y or N)");
String w = scan.nextLine();
while (!"Y".equals(w) || !"y".equals(w) || !"N".equals(w) || !"n".equals(w)) {
System.out.println("Incorrect key, please enter Y for Yes, and N for No.");
w = scan.nextLine();
}
if (w.equalsIgnoreCase("Y") || w.equalsIgnoreCase("y")) {
System.out.println("Welcome back and thank you for flying with us.");
System.out.println("What is your Customer ID?");
int custID = scan.nextInt();
}
If the customer already exists, they are already in this ArrayList.
public class AirlineDriver {
private static Scanner files;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Customer> cust = new ArrayList<Customer>();
Make sure, you have declared all getter method in Customer class. Because, I didn't declared. You need to iterate through the ArrayList<Customer>
for(Customer custom : cust)
{
// call all your getter method from Customer class.
String customerName = custom.getName();
}

How do i store a whole void method in array variable

public void body()
String name = "", address = "",checkin = "", checkout = "";
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
for(k =1;;k++)
{
}
I need to store whole method in a array variable at once.
well actually for every loop i want to create a element in array.
Like chrylis said in his comment you could create a class Reservation with the fields you want to store.
public class Reservation {
private String name;
private String address;
private String checkin;
private String checkout;
public Reservation(String name, String address, String checkin, String checkout) {
this.name = name;
this.address = address;
this.checkin = checkin;
this.checkout = checkout;
}
//getters and setters ...
}
Then you can create a new Object of it in your method and add it to your array
ArrayList<Reservation> reservations = new ArrayList<>();
for(k =1;;k++) {
reservations.add(new Reservation(...));
}
I used an ArrayList instead of an Array because you can add as many elements as you want to an ArrayList

Categories

Resources