Why is my code not displaying these 2 Arraylists? - java

I need to display an ArrayList with a list of college degree/s that an individual may have.
In another ArrayList, I need display the list of individual/s that meet the requirement of college degree that a company is asking.
Tried a system.out inside the loops and it's not even accessing the for loops.
*The 2 methods with the for loops are at the end of this class
import java.util.ArrayList;
public class RecruitingCompany {
private String companyName;
private int phoneNumber;
private String address;
private ArrayList<CollegeDegree> collegeDegreeList = new ArrayList<>();
private ArrayList<Candidate> candidateList = new ArrayList<>();
private Candidate candidate;
private Requirement academicDegree;
public RecruitingCompany(){
/*main constructor*/
}
public RecruitingCompany(String companyName, int phoneNumber, String address){
this.companyName = companyName;
this.phoneNumber = phoneNumber;
this.address = address;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public int getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(int phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public ArrayList<CollegeDegree> getCollegeDegreeList() {
return collegeDegreeList;
}
public void setCollegeDegreeList(ArrayList<CollegeDegree> collegeDegreeList) {
this.collegeDegreeList = collegeDegreeList;
}
public ArrayList<Candidate> getCandidateList() {
return candidateList;
}
public void setCandidateList(ArrayList<Candidate> candidateList) {
this.candidateList = candidateList;
}
public Candidate getCandidate() {
return candidate;
}
public void setCandidate(Candidate candidate) {
this.candidate = candidate;
}
public Requirement getAcademicDegree() {
return academicDegree;
}
public void setAcademicDegree(Requirement academicDegree) {
this.academicDegree = academicDegree;
}
public String showCandidateCollegeDegrees(){
String degree = "Candidato: " + candidate.getName() + "\n";
for (CollegeDegree cd: this.collegeDegreeList){
degree += cd.toString();
}
return degree;
}
public String selectByCollegeDegree(){
String person = "Título: " + academicDegree.getDegree() + "\n";
for (Candidate c: this.candidateList){
person += c.toString();
}
return person;
}
}
The Tester class
public class Tester {
public static void main(String[] args) {
AvailableJob availableJob = new AvailableJob(2005, 2011, "Contador", 444464444, "Metalco", "del poste de luz, 50m oeste", 550.000);
Candidate candidate = new Candidate("Asdrubal", 888888888, "Asdrubal#yahoo.com", "Bachillerato");
CollegeDegree collegeDegree = new CollegeDegree("Bachillerato Administracion", 2003, "Universidad Aguila Calva");
RecruitingCompany recruitingCo = new RecruitingCompany();
Requirement requirement = new Requirement("Bachillerato", 4);
recruitingCo.setCandidate(candidate);
recruitingCo.setAcademicDegree(requirement);
availableJob.setRequirement(requirement);
System.out.println(recruitingCo.showCandidateCollegeDegrees());
System.out.println();
System.out.println(recruitingCo.selectByCollegeDegree());
System.out.println();
System.out.println(availableJob.showRequirement());
//System.out.print(recruitingCo.getCandidateList());
}
}

You are not adding the new candidate or degree to the arraylists. Change the following methods it will work,
public void setAcademicDegree(Requirement academicDegree) {
this.academicDegree = academicDegree;
collegeDegreeList.add(academicDegree);
}
and
public void setCandidate(Candidate candidate) {
this.candidate = candidate;
candidateList.add(candidate);
}
Now when you set a new Candidate object or CollegeDegree object it will be automatically added to the lists.

In your code, you need to do some changes:
setCollegeDegreeList(), setCandidateList() and setCandidate() methods
should be changed to addCollegDegree() and addCandidate()
recruitingCo.setCandidate(candidate) should be replaced to
recruitingCo.addCandidate(candidate);
Need to add recruitingCo.addCollegeDegree(collegeDegree); in main();
And you can get following code:
import java.util.ArrayList;
public class RecruitingCompany {
private String companyName;
private int phoneNumber;
private String address;
private ArrayList<CollegeDegree> collegeDegreeList = new ArrayList<>();
private ArrayList<Candidate> candidateList = new ArrayList<>();
private Requirement academicDegree;
public RecruitingCompany(){
/*main constructor*/
}
public RecruitingCompany(String companyName, int phoneNumber, String address){
this.companyName = companyName;
this.phoneNumber = phoneNumber;
this.address = address;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public int getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(int phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public ArrayList<CollegeDegree> getCollegeDegreeList() {
return collegeDegreeList;
}
public ArrayList<Candidate> getCandidateList() {
return candidateList;
}
public void addCollegeDegree(CollegeDegree collegeDegree) {
this.collegeDegreeList.add(collegeDegree);
}
public void addCandidate(Candidate candidate) {
this.candidateList.add(candidate);
}
public Requirement getAcademicDegree() {
return academicDegree;
}
public void setAcademicDegree(Requirement academicDegree) {
this.academicDegree = academicDegree;
}
public String showCandidateCollegeDegrees(){
String degree = "Candidato: " + candidate.getName() + "\n";
for (CollegeDegree cd: this.collegeDegreeList){
degree += cd.toString();
}
return degree;
}
public String selectByCollegeDegree(){
String person = "Título: " + academicDegree.getDegree() + "\n";
for (Candidate c: this.candidateList){
person += c.toString();
}
return person;
}
}
Tester:
public class Tester {
public static void main(String[] args) {
AvailableJob availableJob = new AvailableJob(2005, 2011, "Contador", 444464444, "Metalco", "del poste de luz, 50m oeste", 550.000);
Candidate candidate = new Candidate("Asdrubal", 888888888, "Asdrubal#yahoo.com", "Bachillerato");
CollegeDegree collegeDegree = new CollegeDegree("Bachillerato Administracion", 2003, "Universidad Aguila Calva");
RecruitingCompany recruitingCo = new RecruitingCompany();
Requirement requirement = new Requirement("Bachillerato", 4);
recruitingCo.addCandidate(candidate);
recruitingCo.addСollegeDegree(collegeDegree);
recruitingCo.setAcademicDegree(requirement);
availableJob.setRequirement(requirement);
System.out.println(recruitingCo.showCandidateCollegeDegrees());
System.out.println();
System.out.println(recruitingCo.selectByCollegeDegree());
System.out.println();
System.out.println(availableJob.showRequirement());
//System.out.print(recruitingCo.getCandidateList());
}
}

Related

How do I leverage a json mapping file to convert from one pojo to another pojo?

I have two POJOs (Person.java and User.java) that contain similar information. See below:
public class Person {
private String first_name;
private String last_name;
private Integer age;
private Integer weight;
private Integer height;
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
}
public class User {
private String name_first;
private String name_last;
private Integer my_age;
private Integer my_weight;
private String social_security;
public String getName_first() {
return name_first;
}
public void setName_first(String name_first) {
this.name_first = name_first;
}
public String getName_last() {
return name_last;
}
public void setName_last(String name_last) {
this.name_last = name_last;
}
public Integer getMy_age() {
return my_age;
}
public void setMy_age(Integer my_age) {
this.my_age = my_age;
}
public Integer getMy_weight() {
return my_weight;
}
public void setMy_weight(Integer my_weight) {
this.my_weight = my_weight;
}
public String getSocial_security() {
return social_security;
}
public void setSocial_security(String social_security) {
this.social_security = social_security;
}
}
I have defined a mapping.json file as shown below using GSON.
{
"columnMap": [
{
"userColumn": "name_first",
"personColumn": "first_name"
},
{
"userColumn": "last_first",
"personColumn": "first_last"
},
{
"userColumn": "my_age",
"personColumn": "age"
},
{
"userColumn": "my_weight",
"personColumn": "weight"
}
]
}
public class Mapping {
private ArrayList<Pair> columnMap;
public Mapping(){
columnMap = new ArrayList<>();
}
public ArrayList<Pair> getColumnMap() {
return columnMap;
}
public void setColumnMap(ArrayList<Pair> columnMap) {
this.columnMap = columnMap;
}
}
I am writing a utility class helper function that converts between a Person and User object the mapped pairs.
public class Pair {
private String userColumn;
private String personColumn;
public String getUserColumn() {
return userColumn;
}
public void setUserColumn(String userColumn) {
this.userColumn = userColumn;
}
public String getPersonColumn() {
return personColumn;
}
public void setPersonColumn(String personColumn) {
this.personColumn = personColumn;
}
public static void main(String args[]){
}
}
My question is below:
As you can see the returnVal object is being set by me (the programmer) to convert from a User POJO to a Person POJO. How do I leverage the pre-defined mapping.json to do this? The reason I am asking is in the future, the mapping.json file may change (maybe the weight mapping no longer exists). So I am trying to avoid re-programming this Utility.userToPerson() function. How can I achieve this? I am thinking Java reflection is the way to go, but I would like to hear back from the Java community.
public class Utility {
public static Person userToPerson(User u){
Person returnVal = new Person();
returnVal.setAge(u.getMy_age()); // <-- Question How do I leverage mapping.json here?
returnVal.setFirst_name(u.getName_first());
returnVal.setLast_name(u.getName_last());
returnVal.setWeight(u.getMy_weight());
return returnVal;
}
}
You can introspect the beans (i.e. User and Person) for the field names and call corresponding getter from User to fetch the value. Later call corresponding setter in Person.
Here I have taken userToPersonFieldsMap for mapping the field, you can load mapping from JSON file and construct the map accordingly.
Important code section is the for loop, where it dynamically calls getter and setter and does the job.
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
public class UserToPersonMapper {
public static void main(String[] args) throws IntrospectionException, InvocationTargetException, IllegalAccessException {
Map<String, String> userToPersonFieldsMap = new HashMap<>();
userToPersonFieldsMap.put("name_first", "first_name");
userToPersonFieldsMap.put("last_first", "first_last");
userToPersonFieldsMap.put("age", "personAge");
//existing user
User user = new User("Tony", "Stark", 20);
//new person - to be initialised with values from user
Person person = new Person();
for (Map.Entry<String, String> entry : userToPersonFieldsMap.entrySet()) {
Object userVal = new PropertyDescriptor(entry.getKey(), User.class).getReadMethod().invoke(user);
new PropertyDescriptor(entry.getValue(), Person.class).getWriteMethod().invoke(person, userVal);
}
System.out.println(user);
System.out.println(person);
}
}
class User {
private String name_first;
private String last_first;
private int age;
public User(String name_first, String last_first, int age) {
this.name_first = name_first;
this.last_first = last_first;
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName_first() {
return name_first;
}
public String getLast_first() {
return last_first;
}
public void setName_first(String name_first) {
this.name_first = name_first;
}
public void setLast_first(String last_first) {
this.last_first = last_first;
}
#Override
public String toString() {
return "User{" +
"name_first='" + name_first + '\'' +
", last_first='" + last_first + '\'' +
", age=" + age +
'}';
}
}
class Person {
private String first_name;
private String first_last;
private int personAge;
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public void setFirst_last(String first_last) {
this.first_last = first_last;
}
public String getFirst_name() {
return first_name;
}
public String getFirst_last() {
return first_last;
}
public int getPersonAge() {
return personAge;
}
public void setPersonAge(int personAge) {
this.personAge = personAge;
}
#Override
public String toString() {
return "Person{" +
"first_name='" + first_name + '\'' +
", first_last='" + first_last + '\'' +
", personAge=" + personAge +
'}';
}
}
You can tweak and try it out this example to make it more align with your requirement.
Note:
This solution uses reflection.

Age filter in Java with ArrayList

I want to make a method that tells me who is the oldest person in the ArrayList and who is the youngest person. The method will receive the arraylist that i want to apply the method, i have 3 in my code, each one is an contact list.
The method is suppose to return the name of the person, but i don't know how to do it. Familia, Profissional and Amigos are my arraylists and "idade" = age and "nome" = name.
package com.company;
public class Contato {
public String nome;
public int idade;
public String sexo;
public String profissao;
public String telefone;
public String email;
public Contato(String nome, int idade, String sexo, String profissao, String telefone, String email) {
this.nome = nome;
this.idade = idade;
this.sexo = sexo;
this.profissao = profissao;
this.telefone = telefone;
this.email = email;
}
#Override
public String toString() {
return "" +
nome + ',' +
idade + " anos de idade, " +
"do sexo " + sexo + ',' +
profissao + ',' +
" telefone nº " + telefone + ", " +
"e-mail:" + email;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public int getIdade() {
return idade;
}
public void setIdade(int idade) {
this.idade = idade;
}
public String getSexo() {
return sexo;
}
public void setSexo(String sexo) {
this.sexo = sexo;
}
public String getProfissao() {
return profissao;
}
public void setProfissao(String profissao) {
this.profissao = profissao;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
package com.company;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class GestaoContatos extends Contato {
ArrayList<Contato> Familia = new ArrayList();
ArrayList<Contato> Amigos = new ArrayList();
ArrayList<Contato> Profissional = new ArrayList();
public GestaoContatos(Contato c) {
super(c.nome, c.idade, c.sexo, c.profissao, c.telefone, c.email);
}
public void adicionaContato(String nomeAgenda, Contato contato) {
if( nomeAgenda == "Familia"){
Familia.add(contato);
} else
if(nomeAgenda == "Amigos"){
Amigos.add(contato);
} else
if(nomeAgenda == "Profissional") {
Profissional.add(contato);
} else
System.out.println("Indispnível");
}
public void eliminaContato(String nomeContato) {
for(int i = 0; i < Familia.size(); i++) {
if(getFamilia().contains(nomeContato)) {
Familia.remove(nomeContato);
}
}
}
public void printaLista(String nomeAgenda){
if(nomeAgenda.equals("Familia")) {
Familia.forEach(System.out::println);
}
if(nomeAgenda.equals("Amigos")) {
Amigos.forEach(System.out::println);
}
if(nomeAgenda.equals("Profissional")) {
Profissional.forEach(System.out::println);
}
else {
throw new RuntimeException("Opcao invalida");
}
}
public void tooString() {
var contatos = new ArrayList<Contato>();
Familia.forEach(it -> contatos.add(it));
Amigos.forEach(it -> contatos.add(it));
Profissional.forEach(it -> contatos.add(it));
System.out.println(contatos.toString());
}
public void olderPerson(String nomeAgenda){
int i = 0;
if (nomeAgenda.equals("Amigos")) {
for (i = 0; Familia.size(); i++) {
Familia.stream().filter();
}
}
}
public void geraListaBinaria() throws IOException {
var file = new File("C:\\Users\\Jorge Luiz\\Desktop\\contatos.txt");
var writer = new FileWriter(file.getName());
writer.write(this.getProfissional().toString());
writer.write(this.getFamilia().toString());
writer.write(this.getProfissional().toString());
writer.close();
}
public ArrayList<Contato> getFamilia() {
return Familia;
}
public void setFamilia(ArrayList<Contato> familia) {
Familia = familia;
}
public ArrayList<Contato> getAmigos() {
return Amigos;
}
public void setAmigos(ArrayList<Contato> amigos) {
Amigos = amigos;
}
public ArrayList<Contato> getProfissional() {
return Profissional;
}
public void setProfissional(ArrayList<Contato> profissional) {
Profissional = profissional;
}
}
If you want to return oldest person in one list:
public Contato oldestPerson(String nomeAgenda){
return Familia.stream()
.filter(c -> c.getNome().equals(nomeAgenda)) // contatos named nomeAgenda
.max(Comparator.comparingInt(Contato::getIdade)) // take oldest
.get();
}
For all lists you can do:
public Contato oldestPerson(){
return Stream.of(Familia, Amigos, Profissional)
.flatMap(Collection::stream) // flatting to one long stream
.filter(c -> c.getNome().equals(nomeAgenda)) // contatos named nomeAgenda
.max(Comparator.comparingInt(Contato::getIdade))
.get();
}
EDIT
Based on the comment, we should change a couple of things to achieve what you want. First, we should define a Map<String, List<Contato>> and populate it in the constructor:
private Map<String, List<Contato>> contatoGroups;
private static final String familiaKey = "Familia";
private static final String amogisKey = "Amigos";
private static final String profissionalKey = "Profissional";
public GestaoContatos(Contato c) {
super(c.nome, c.idade, c.sexo, c.profissao, c.telefone, c.email);
contatoGroups.put(familiaKey, new ArrayList<>());
contatoGroups.put(amogisKey, new ArrayList<>());
contatoGroups.put(profissionalKey, new ArrayList<>());
}
(Consider using enum instead of String as key in the map)
Then wherever you want to get a group, for example: Familia, you should do:
List<Contato> contatoes = contatoGroups.get(familiaKey);
And then we should change the oldestPerson() like this:
public Contato oldestPerson(String nomeAgenda){ // nomeAgenda could be "Familia", "Amigos"...
List<Contato> selectedGroup = contatoGroups.get(nomeAgenda);
return selectedGroup.stream()
.max(Comparator.comparingInt(Contato::getIdade)) // take oldest
.get();
}

How to solve Could not find or load main class in Java oop?

my program about to write the java implementation classes, I wrote 4 files,
Mycompanymain -> this will show the output for the other files.
Company -> this will be company.java which contains the name of the company.
address -> this will contains the address of the person who works for the company.
supplier -> this will be to link the two classes [ company, address ].
I got those errors:
MyCompanyMain.java:29: error: bad initializer for for-loop
for(Suppliers : company.getSuppliers())
^
1 error
Error: Could not find or load main class MyCompanyMain
Caused by: java.lang.ClassNotFoundException: MyCompanyMain
This is Mycompanymain.java :
import java.util.ArrayList;
import static java.lang.System.out;
public class MyCompanyMain
{
public static void main(String[] args)
{
Company company = new Company();
company.setName("ABC sdn bhd");
Address address = new Address(123, "Jalan UTeM", "Durian Tunggal",76100, "Melaka", 06123456);
company.setAddress(address);
ArrayList<Supplier> suppliers = new ArrayList<Supplier>();
Supplier supplierBuku = new Supplier();
supplierBuku.setSupplierName("Syarikat Buku Sdn Bhd");
Address supplierBukuAddress = new Address(3, "Jalan Munsyi", "Ayer Keroh", 75400, "Melaka", 06123123);
supplierBuku.setAddress(supplierBukuAddress);
Supplier supplierComputer = new Supplier();
supplierComputer.setSupplierName("Syarikat Computer Sdn Bhd");
Address supplierComputerAddress = new Address(3, "Jalan Bukit Beruang","Ayer Keroh", 75400, "Melaka", 06111223);
supplierComputer.setAddress(supplierComputerAddress);
suppliers.add(supplierBuku);
suppliers.add(supplierComputer);
Company.setSuppliers(suppliers);
Address comp_Address = company.getAddress();
out.println(comp_Address.getNoShop()+" :"+comp_Address.getRoad()+" : "+comp_Address.getDistrict()+" :"+comp_Address.getPhone());
for(Suppliers : company.getSuppliers())
{
out.print(s.getSupplierName()+" \t: ");
Address supp_Address = s.getAddress();
out.println(supp_Address.getNoShop()+" :"+supp_Address.getRoad()+" : "+supp_Address.getDistrict()+" :"+supp_Address.getPhone());
}
}
}
this is Company.java:
import java.util.* ;
public class Company {
private String name ;
private Address address ;
private ArrayList<Supplier> suppliers ;
public Company() {
suppliers = new ArrayList<Supplier>();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public ArrayList<Supplier> getSuppliers() {
return suppliers;
}
public void setSuppliers(ArrayList<Supplier> suppliers) {
this.suppliers = suppliers;
}
}
This is Address.java:
public class Address {
private int noShop ;
private String road ;
private String district ;
private int posCode ;
private String state ;
private int phone ;
public Address(int noShop, String road, String district, int posCode, String state, int phone) {
this.noShop = noShop;
this.road = road;
this.district = district;
this.posCode = posCode;
this.state = state;
this.phone = phone;
}
public int getNoShop() {
return noShop;
}
public String getRoad() {
return road;
}
public String getDistrict() {
return district;
}
public int getPosCode() {
return posCode;
}
public String getState() {
return state;
}
public int getPhone() {
return phone;
}
}
This is supplier.java:
public class Supplier {
private String supplierName ;
private Address address ;
public Supplier() {
}
public String getSupplierName() {
return supplierName;
}
public void setSupplierName(String supplierName) {
this.supplierName = supplierName;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
You are missing a variable in your for loop, use this
for(Suppliers supplier : company.getSuppliers()) {
// rest of code here
}
The issue here isn't the main method, it's that your code fails to compile, since you're missing a type declaration for the enhanced for loop. It seems like you're missing a space between Supplier (the type) and s (the declared variable):
for(Supplier s : company.getSuppliers())
// Here ----^
{
out.print(s.getSupplierName()+" \t: ");
Address supp_Address = s.getAddress();
out.println(supp_Address.getNoShop()+" :"+supp_Address.getRoad()+" : "+supp_Address.getDistrict()+" :"+supp_Address.getPhone());
}

Unable to initialize an object through constructors in Java: Erroneous Compilation

This code below keeps throwing the following error:
Java Error Terminal Screen Snapshot
I've tried quite a few online fixes but they don't seem to be working.
My code is below and I've commented the error location(occurs in the driver main function)
NOTE: The code compiles properly if I change public static void main(String args[]) to public void main(String args[]) but when i run it, it throws the error "Change main to static void main". I'm a little stuck here.
import java.util.*;
class Exercise{ //Exercise Begins
class UtilityFunctions{
public String getAuthor(){ return "";};
public String getPublisher(){return "";};
public void display(){};
}
class Book extends UtilityFunctions{
private String title;
private String author;
private String category;
private String datePublished;
private String publisher;
private double price;
public Book(String authorParam, String publisherParam){
author = authorParam;
publisher = publisherParam;
}
//List of Setters
public void setTitle(String title){
this.title = title;
}
public void setCategory(String cat){
this.category = cat;
}
public void setDatePublished(String dp){
this.datePublished = dp;
}
public void setPrice(double p){
this.price = p;
}
//List of Getters
public String getTitle(){
return this.title;
}
#Override
public String getAuthor(){
return this.author;
}
public String getCategory(){
return this.category;
}
public String getDatePublished(){
return this.datePublished;
}
#Override
public String getPublisher(){
return this.publisher;
}
public double getPrice(){
return this.price;
}
#Override
public void display(){
System.out.println("Book Title:" + getTitle());
System.out.println("Author:" + getAuthor());
System.out.println("Category:" + getCategory());
System.out.println("Date Published:" + getDatePublished());
System.out.println("Publisher:" + getPublisher());
System.out.println("Price:$" + getPrice());
}
}
class Author extends UtilityFunctions{
private String authorName;
private String birthDate;
private String publisher;
private String email;
private String gender;
List<Book> bookList;
public Author(String publisherParam){
publisher = publisherParam;
}
public void addBook(Book b){
bookList.add(b);
}
//List of Setters
public void setName(String n){
this.authorName = n;
}
public void setEmail(String em){
this.email = em;
}
public void setGender(String gen){
this.gender = gen;
}
public void setBirthDate(String dob){
this.birthDate = dob;
}
//List of Getters
public String getAuthor(){
return this.authorName;
}
public String getPublisher(){
return this.publisher;
}
public String getEmail(){
return this.email;
}
public String getGender(){
return this.gender;
}
public String getBirthDate(){
return this.birthDate;
}
#Override
public void display(){
System.out.println("Author Name:" + getAuthor());
System.out.println("Email:" + getEmail());
System.out.println("Gender:" + getGender());
System.out.println("BirthDate:" + getBirthDate());
System.out.println("Publisher:" + getPublisher());
System.out.println("BOOKS:");
for(Book b:bookList){
b.display();
System.out.println();
}
}
}
class Publisher extends UtilityFunctions{
private String publisherName;
private String publisherAddress;
private String publisherEmail;
private int publisherPhoneNumber;
List<Author> authorList;
public Publisher(String name, String add, String email,int phone){
publisherName = name;
publisherAddress = add;
publisherEmail = email;
publisherPhoneNumber = phone;
}
public void addAuthor(Author a){
authorList.add(a);
}
//List of Getters
public String getPublisher(){
return this.publisherName;
}
public String getAddress(){
return this.publisherAddress;
}
public String getEmail(){
return this.publisherEmail;
}
public int getPhoneNumber(){
return this.publisherPhoneNumber;
}
#Override
public void display(){
System.out.println("Publisher Name:" + getPublisher());
System.out.println("Publisher Address:" + getAddress());
System.out.println("Publisher Phone Number:" + getPhoneNumber());
System.out.println("Publisher Email:" + getEmail());
System.out.println("AUTHORS:");
for(Author a:authorList){
a.display();
System.out.println("-------------------------------------");
}
System.out.println("--------------------------------------------------------------------------------");
System.out.println("--------------------------------------------------------------------------------");
}
}
public static void main(String args[]){
ArrayList<Publisher> publisherList = new ArrayList<Publisher>();
//1st ERROR HERE
Publisher pub1 = new Publisher("Riverhead Books","8080 Cross Street","riverhead#riverheadbooks.co.uk",784646533);
//2nd ERROR HERE
Author author1 = new Author(pub1.getPublisher());
author1.setName("Khaled Hosseini");
author1.setGender("Male");
author1.setBirthDate("1965-10-09");
author1.setEmail("khaledhosseini#gmail.com");
pub1.addAuthor(author1);
//3rd ERROR HERE
Book book1 = new Book(author1.getAuthor(),author1.getPublisher());
book1.setTitle("Kite Runner");
book1.setCategory("Historical-Fiction|Drama");
book1.setPrice(39.95);
book1.setDatePublished("2003-05-29");
author1.addBook(book1);
publisherList.add(pub1);
for(Publisher p:publisherList){
p.display();
}
}
}//Exercise Ends
All your classes : Book, Author, Publisher, UtilityFunctions ... should be outside the Exercise class
Class Exercise {
public static void main(String args[]) {...}
} // end class exercice
Class UtilityFunctions {...}
Class Book {...}
Class Author {...}
Class Publisher {...}

How can I create a instance of a class with an array of Strings as the only instance variable?

I have written a class Form. An array of 10 Strings is the only parameter in the constructor. How can I create an instance of the class? I'm sure there are other problems in my setters and getters but I cant test them until I fix this.
public class FormLab {
public static void main(String[]args){
Form f1 = new Form(String webForm);
System.out.println(print(String[] webForm));
System.out.println("Any Empty Strings? " + f1.getEmptyFields);
System.out.println("Number of characters in userID? " + f1.getCharNum);
System.out.println("Do password fields match? " + f1.getPwCheck);
System.out.println("Does email contain correct characters? " + f1.getEmailCheck);
}
}
public class Form {
String[] webForm = new String[10];
private String userID;
private String pw;
private String pw2;
private String email;
private String name;
private String address;
private String city;
private String state;
private String zip;
private String telephone;
//constructor
public Form(String[] webForm){
//filling array with field values
webForm[0] = "0123456789";
webForm[1] = "java123";
webForm[2] = "java123";
webForm[3] = "luke.skywalker#jedi.com";
webForm[4] = "Luke Skywalker";
webForm[5] = "1234 The Force Way";
webForm[6] = "Rome";
webForm[7] = "GA";
webForm[8] = "30161";
webForm[9] = "7065551234";
}
public boolean getEmptyFields() {
//boolean empty = false;
for(int i = 0; i < webForm.length; i++){
if(webForm[i]!= null){
return true;
}
}
return false;
}
public String getUserID(){
return userID;
}
public void setUserId(String userID){
this.userID = userID;
}
public String getPw(){
return pw;
}
public void setPw(String pw){
this.pw = pw;
}
public String getPw2(){
return pw2;
}
public void setPw2(String pw2){
this.pw2 = pw2;
}
public String getEmail(){
return email;
}
public void setEmail(String email){
this.email = email;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getAddress(){
return address;
}
public void setAddress(String address){
this.address = address;
}
public String getCity(){
return city;
}
public void setCity(String city){
this.city = city;
}
public String getState(){
return state;
}
public void setState(String state){
this.state = state;
}
public String getZip(){
return userID;
}
public void setZip(String zip){
this.zip = zip;
}
public String getTelephone(){
return telephone;
}
public void setTelephone(String telephone){
this.telephone = telephone;
}
public int getCharNum(String userID) {
int userLength = 0;
//userID.length();
return userLength;
}
public boolean getPwCheck() {
boolean check = pw.equalsIgnoreCase(pw2);
// pw.equalsIgnoreCase(pw2);
return check;
}
public boolean getEmailCheck(String email) {
if(email.contains("#") && email.contains(".")){
return true;
}
return false;
}
public static void getPrint(String[] webForm) {
System.out.println(webForm.toString());
}
}
Use method arraycopy.
public Form(String[] webForm){
System.arraycopy(webForm, 0, this.webForm, 0, webForm.length);
}
The constructor takes a string array as argument, but you are passing it a string, try:
myList = new String[];
myForm = new Form(myList);
You need to declare your array before putting it as a parameter as follow:
public class FormLab {
public static void main(String[]args){
String webForm = new String[10];
Form f1 = new Form(webForm);
/*System.out.println(print(String[] webForm)); THIS IS WRONG*/
/*TO PRINT THE VALUES IN THE ARRAY YOU NEED TO WRITE A METHOD IN UR
FORM CLASS THAT WILL LOOP THRU UR VARIABLE AND PRINT*/
System.out.println("Any Empty Strings? " + f1.getEmptyFields);
System.out.println("Number of characters in userID? " + f1.getCharNum);
System.out.println("Do password fields match? " + f1.getPwCheck);
System.out.println("Does email contain correct characters? " + f1.getEmailCheck);
}

Categories