The constructor AddPatron(String, String) is undefined - java

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.

Related

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() ).

Java - Reading in a CSV file into a constructor

Java (Constructor issue)
Trying to figure out how to read in a CSV file into a constructor. Theme is harry potter and I'm reading in 4 files (Gryffindor, Hufflepuff, Ravenclaw, Slytherin). Reading this into my House.java, but School.java and Student.java have constructors/getters and setters as well. Supplied below. For instance a within a School exists a House and within that exists a Student. In the 4 CSV files provided, each file is a name of a "House" in which you would read in the file as "Students" (first name, last name, year).
These 3 java files are within application.model to support an application in JavaFX using the MVC format. It's specifically tailored in this fashion for the sake of grading.
House.java
public class House {
private String name;
private String color;
private String professor;
public ArrayList<Student> Students;
public House(String name, String color, String professor, ArrayList stdList) {
this.name = name;
this.color = color;
this.professor = professor;
this.Students = stdList;
}
public ArrayList<Student> sortStudents(ArrayList<Student> allStudents) {
if (allStudents != null) {
Collections.sort(allStudents, new SortTool());
}
return allStudents;
}
public void dataLoader() {
String fileName = "Gryffindor.csv";
String content = null;
/*
* Shows working path System.out.println(newFile(".").getAbsoluteFile());
*/
try {
Scanner inputStream = new Scanner(new File(fileName));
// Delimits by commas and (enter or \n)
inputStream.useDelimiter("[,\n]");
// Iteration rather than iterable
while (inputStream.hasNext()) {
content = inputStream.nextLine();
}
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
School.java
public class School {
private String name;
private int enrollment;
private House houses[];
/*
* School Constructor
*
* #param pass in name to set name
*/
public School(String name) {
this.name = name;
houses = new House[4];
enrollment = 0;
}
}
Student.java
public class Student {
private String firstName;
private String lastName;
private int year;
public Student(String firstName, String lastName, int year) {
this.firstName = firstName;
this.lastName = lastName;
this.year = year;
}
}
SortTool.java
public class SortTool implements Comparator {
#Override
public int compare(Student a, Student b) {
int c = a.getYear() - b.getYear();
if (c == 0)
c = a.getLastName().compareTo(b.getLastName());
if (c == 0)
c = a.getFirstName().compareTo(b.getFirstName());
return c;
}
}
Trying to be discrete about the entire program since I wrote it and don't want it to be tracked as plagerism.
House.java - how do I read into this CSV file into a constructor. Comma delmited and needs to be read in and not manually entered.
Example of Gryffindor.csv
Colin Creevy,1, Hermione Granger,2, Harry Potter 2,
Well you can read the file the constructor of the House class. Just add a private method that will populate the Students arrayList.
You have to open the file giving the path of where each houses files are located and append it with "/"+this.name+".csv", and then for each line of the file you read, you parse it and add a new Student in the arraylist.
Example of the method :
private void populateHouseFromFile(){
String line;
br = new BufferedReader(new FileReader(PATH_TO_HOUSES+"/"+this.name+".csv"));
while ((line = br.readLine()) != null) {
String[] split = line.split(",",3); //Retrieve each part of the student information , assuming each field is separated with a "," and each line is new entry.
this.Students.add(new Student(split[0],split[1],Integer.decoded(split[2])));
}
}
You should check that int the constructor of student that the argument passed are not stupid (negative year, etc if bad constructed .csv).

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

Arraylist java program

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

Loading a moviedatabase txt file in Java and sorting it

The goal of this project is to read a movie data base txt file, where each line in the file contains the name, year released, and associated actors for one movie. Each piece of information is separated by ‘/’ characters. The year is specified inside parentheses at the end of the movie name. I have already created an actor class, which stores a String firstname and a String lastname, and a movie class which holds all the above info about the movie. In the movieDataBase class, I need to load the .txt file, and split it in to the different components. I understand how to split the file in to different elements, I just don't know how to turn the string of associated actors into and arrayList of Actor objects. Sorry for the newbie question. My java book doesn't talk about it at all and I have been looking for the past 3 hours on the internet! Here's my code:
public class Actor {
private String firstName;
private String lastName;
public Actor(){
firstName = "";
lastName = "";
}
public Actor( String first){
this (first, "");
}
public Actor( String first, String last){
firstName = first;
lastName = last;
}
public String getFirstName(){
return firstName;
}
public void setFirstName( String first){
firstName = first;
}
public String getLastName(){
return lastName;
}
public void setLastName( String last){
lastName = last;
}
public String toString(){
return firstName + " " + lastName;
}
}
//new class
public class MovieDatabase
public void loadDataFromFile( String aFileName) throws FileNotFoundException{
//creating a scanner to read the file
Scanner theScanner = new Scanner(aFileName);
theScanner = new Scanner(new FileInputStream("cast-mpaa.txt"));
while(theScanner.hasNextLine()){
String line = theScanner.nextLine();
String[] splitting = line.split("/");
String movieTitle = splitting[0];
filmActors.add(splitting[2]);
//this is where I have issues
ArrayList<Actor> associatedActors = new ArrayList<Actor>();
for( String newActors : filmActors){
}
}
}
}
You could do something like:
for( String newActor : filmActors){
associatedActors.add(new Actor(newActor));
}
This means with new Actor you are creating a new object instance of Actor and adding it to the array List that you created.
To Actor class, you are passing the actor name in constructor and that's how you are constructing the Actor object i assume.

Categories

Resources