How can I solve with Java's map containsKey() method? - java

I checked the code and saving data to the HashMap is correct, when typing ADD. Then after choosing option FIND I can get to the dedicated function but the method is unable to show me found object even if it is correct 100%.
Please check this code out and tell me why it does not find right objects in "public void showInfo(String name, String secondName)" for class Company that is sparked by TYPING "FIND" in class CompanyApp
import java.util.InputMismatchException;
import java.util.Objects;
import java.util.Scanner;
public class CompanyApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
options[] values = options.values();
int choose;
int EXIT_NR = 2;
Company ref = new Company();
do {
System.out.println("Available options: ");
for (options one : values) {
System.out.println(one.getDescription() + " - " + one.name());
}
System.out.println("Choose one: ");
try {
choose = options.valueOf(in.nextLine()).ordinal();
if (Objects.equals(EXIT_NR, choose)) break;
if (choose < 0 || choose >= options.values().length) {
throw new IllegalArgumentException("Choose 0, 1 or 2!");
}
options(choose);
} catch (InputMismatchException e) {
System.out.println("Choose a number ");
}
} while (1 == 1);
}
static void options(int choose){
Company ref = new Company();
Scanner info = new Scanner(System.in);
switch (choose){
case 0:
System.out.println("Type in the name of the worker: ");
String name = info.nextLine();
System.out.println("Type in the second name of the worker: ");
String secondName = info.nextLine();
System.out.println("Type in the salary: ");
double salary = info.nextDouble();
info.nextLine();
ref.add(new Employee(name, secondName, salary));
break;
case 1:
System.out.println("Type in the name of the worker you want to find: ");
String name2 = info.nextLine();
System.out.println("Type in the second name of the worker you want to
find: ");
String secondName2 = info.nextLine();
ref.showInfo(name2, secondName2);
break;
}
}
}
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class Company {
private Map<String, Employee> map = new HashMap<>();
public void add(Employee employee){
String key = employee.getName() + " " + employee.getSecondName();
if(!map.containsKey(key)){
map.put(key, employee);
System.out.println("Added object to map");}
}
public void showInfo(String name, String secondName){
String key = name + " " + secondName;
System.out.println("in showinfo method");
if(map.containsKey(key)){
System.out.println("found an object");
Employee employee = map.get(key);
System.out.println(employee.getName());
}}}
enum options {
ADD("Add employee "), FIND("Find employee"), EXIT("Exit program");
private String description;
options(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "options{" +
"description='" + description + '\'' +
'}';
}
}
String name;
String secondName;
double salary;
public Employee(String name, String secondName, double salary) {
this.name = name;
this.secondName = secondName;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSecondName() {
return secondName;
}
public void setSecondName(String secondName) {
this.secondName = secondName;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
#Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", secondName='" + secondName + '\'' +
", salary=" + salary +
'}';
}
}

The problem is in the method static void options(int choose). You need to pass the Company-Object and use it there like this:
Call from main method (ref is the Company-Object you create in the main method)
options(choose, ref);
The options-method with the Company as second parameter:
static void options(int choose, Company ref){
Scanner info = new Scanner(System.in);
switch (choose){
case 0:
System.out.println("Type in the name of the worker: ");
String name = info.nextLine();
System.out.println("Type in the second name of the worker: ");
String secondName = info.nextLine();
System.out.println("Type in the salary: ");
double salary = info.nextDouble();
info.nextLine();
//use the passed Company here
ref.add(new Employee(name, secondName, salary));
break;
case 1:
System.out.println("Type in the name of the worker you want to find: ");
String name2 = info.nextLine();
System.out.println("Type in the second name of the worker you want to find: ");
String secondName2 = info.nextLine();
//and here
ref.showInfo(name2, secondName2);
break;
}
}
Explanation what is happening in your code
As mentioned, the problem is in the method static void options(int choose).
Here you create a new Company-Object which is not passed in any way to the main method.
This is what happens, when you use ADD and a FIND afterwards:
Call options from main method with ADD
new Company-Object is created in options
new Employee-Object is added to the Company from the previous point
the method ends -> the created Company-Object is "thrown away" (eligible for Garbage Collection)
Call options from main method with FIND
new Company-Object is created in options(therefore no Employees in it)
no Employee can be found, because there is no entry in the map of the newly created Company

The map is empty at the time when you're trying to get the data from it using FIND option. The reason for that is you recreate the Company object in the options method:
Company ref = new Company();
At the same time also the map is recreated so there are no records inside.
Also, the Company object in the main method is not used.

Related

Exception in thread "main" java.lang.NullPointerException when trying to run code in compiler [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed last year.
Running into trouble with the output of my code (listed below, separate files and all) where I can execute the correct action up until I need to execute one directly after another. It's spitting out the Exception in thread "main" java.lang.NullPointerException error along with at which lines it is incorrect, however I don't know how to fix it as of now. (This is done in Eclipse compiler)
public class Assignment4
{
public static void main (String[] args)
{
// local variables, can be accessed anywhere from the main method
char input1 = 'Z';
//String inputInfo= "";
String name, firstName, lastName, city ;
int years = 0;
String line = new String();
// instantiate a Team object
Team suns = null;
printMenu();
//Create a Scanner object to read user input
Scanner scan = new Scanner(System.in);
do // will ask for user input
{
System.out.println("What action would you like to perform?");
line = scan.nextLine();
if (line.length() == 1)
{
input1 = line.charAt(0);
input1 = Character.toUpperCase(input1);
// matches one of the case statement
switch (input1)
{
case 'A': //Add a coach
System.out.print("Please enter the Coach's information:\n");
System.out.print("Enter coach's first name:\t");
firstName = scan.nextLine();
System.out.print("Enter coach's last name:\t");
lastName = scan.nextLine();
System.out.print("Enter coach's years of experience:\t");
years = scan.nextInt();
scan.nextLine();
Coach sunsCoach = new Coach(firstName, lastName, years);
System.out.print("\nPlease enter the Team's information:");
System.out.print("\nEnter teams name:\t");
name = scan.nextLine();
System.out.print("Enter Team's city:\t");
city = scan.nextLine();
suns = new Team(name, sunsCoach, city);
break;
case 'D': //Display course
System.out.print(suns.toString());
break;
case 'Q': //Quit
break;
case '?': //Display Menu
printMenu();
break;
default:
System.out.print("Unknown action\n");
break;
}
}
else
{
System.out.print("Unknown action\n");
}
} while (input1 != 'Q' || line.length() != 1);
scan.close();
}
/** The method printMenu displays the menu to a user **/
public static void printMenu()
{
System.out.print("Choice\t\tAction\n" +
"------\t\t------\n" +
"A\t\tAdd Coach\n" +
"D\t\tDisplay Team\n" +
"Q\t\tQuit\n" +
"?\t\tDisplay Help\n\n");
}
}
Along with this code, there are my two child class files, Coach.java and Team.java respectively, listed below.
public class Coach
{ String firstName, lastName; //constructor
int years;
{ String numYears;
firstName = lastName = numYears = "?";
}
public Coach(String first, String last, int years) { //Set variables
firstName = first;
lastName = last;
int numYears = years;
}
//Accessors
public String getFirstName()
{return firstName;}
public String getLastName()
{return lastName;}
public String getYears()
{String numYears = null;
return numYears;}
// Mutators
public void setFirstName(String theFirstName)
{firstName = theFirstName;}
public void setLastName(String theLastName)
{lastName = theLastName;}
public void setYears(int years)
{int numYears = years;}
public String toString() {
String output = "\nLast Name:\t" + lastName + "\nFirst Name:\t " + firstName;
output += "\nYears of Experience:\t " + getYears() + "\n";
return output;
}
}
public class Team {
String teamName;
Coach coach;
String getCity;
//Constructor
public Team() {
teamName = getCity = "?";
}
public Team(String name, Coach coach, String cityName)
{ teamName = name;
}
//Accessors
public String getName() {return teamName;}
public Coach getCoach() {return coach;}
public String getCity() {return getCity;}
//Mutators
public void setName(String theName) {teamName = theName;}
public void setCity(String someCity) {getCity = someCity;}
public void setCoach(String firstName, String lastName, int years)
{ coach = new Coach (firstName, lastName, years);
}
public String toString()
{ String output = "Team's name:\t" + teamName + " at " + getCity() + "\nCoach Information:";
output += coach.toString();
return output;
}
}
Running the code, and putting in inputs until I wish to select option D, will eventually yield this specific error:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Coach.toString()" because "this.coach" is null
at Team.toString(Team.java:30)
at Assignment4.main(Assignment4.java:68)
suns = new Team(name, sunsCoach, city);
As I can see you are passing sunsCoach as a parameter to the constructor of Team, but you are not initialising the coach object.
Update your code from
public Team(String name, Coach coach, String cityName)
{
teamName = name;
}
to
public Team(String name, Coach coach, String cityName)
{
teamName = name;
coach = coach;
getCity = cityName;
}
this would resolve the NullPointerException

Why do I keep getting null instead of the output I want?

This assignment requires me to take in input and print it out. The first half of the output is printing currently, but the other half is giving me null. What's wrong here?
Heres my code:
This is the main class.
import java.util.*;
public class Assignment4 {
public static void main(String[] args) {
// local variables, can be accessed anywhere from the main method
char input1 = 'Z';
// String inputInfo= "";
String courseName, firstName, lastName, office, university;
String line = new String();
// instantiate a Course object
Course cse110 = null;
printMenu();
// Create a Scanner object to read user input
Scanner scan = new Scanner(System.in);
do // will ask for user input
{
System.out.println("What action would you like to perform?");
line = scan.nextLine();
if (line.length() == 1) {
input1 = line.charAt(0);
input1 = Character.toUpperCase(input1);
// matches one of the case statement
switch (input1) {
case 'A': // Add a course
System.out.print("Please enter the Instructor information:\n");
System.out.print("Enter instructor's first name:\t");
firstName = scan.nextLine();
System.out.print("Enter instructor's last name:\t");
lastName = scan.nextLine();
System.out.print("Enter instructor's office number:\t");
office = scan.nextLine();
Instructor myInstructor = new Instructor(firstName, lastName, office);
System.out.print("\nPlease enter the Course information:");
System.out.print("\nEnter course name:\t");
courseName = scan.nextLine();
System.out.print("Enter university name:\t");
university = scan.nextLine();
cse110 = new Course(courseName, myInstructor, university);
break;
case 'D': // Display course
System.out.print(cse110.toString());
break;
case 'Q': // Quit
break;
case '?': // Display Menu
printMenu();
break;
default:
System.out.print("Unknown action\n");
break;
}
} else {
System.out.print("Unknown action\n");
}
} while (input1 != 'Q' || line.length() != 1);
scan.close();
}
/** The method printMenu displays the menu to a user **/
public static void printMenu() {
System.out.print("Choice\t\tAction\n" + "------\t\t------\n" + "A\t\tAdd Course\n" + "D\t\tDisplay Course\n"
+ "Q\t\tQuit\n" + "?\t\tDisplay Help\n\n");
}
}
Heres the Course class:
import java.util.*;
public class Course
{
//----------------------------------------------------------------------
// ATTRIBUTES
private String courseName;
private Instructor instructor;
private String university;
//----------------------------------------------------------------------
// CONSTRUCTOR
public Course()
{
courseName = "?";
university = "?";
instructor = null;
}
public Course(String name, Instructor inst, String univer)
{
this.setName(name);
this.setInstructor(name, Instructor.lastName, Instructor.officeNum);
this.setUniversity(univer);
}
//----------------------------------------------------------------------
// ACCESSORS
public String getName()
{
return courseName;
}
public String getUniversity()
{
return university;
}
public Instructor getInstructor()
{
return instructor;
}
//----------------------------------------------------------------------
//METHODS
public void setName(String someName)
{
this.courseName = someName;
}
public void setUniversity(String someUniversity)
{
this.university = someUniversity;
}
public void setInstructor(String firstName, String lastName, String office)
{
Instructor.firstName = firstName;
Instructor.lastName = lastName;
Instructor.officeNum = office;
}
public String toString()
{
return "Course name:\t" + courseName + " at " + university + "\nInstructor Information:" + instructor + "\n";
}
}
Heres the Instructor class:
import java.util.*;
public class Instructor
{
//----------------------------------------------------------------------
// ATTRIBUTES
public static String firstName;
public static String lastName;
public static String officeNum;
//----------------------------------------------------------------------
// CONSTRUCTOR
public Instructor()
{
firstName = "?";
lastName = "?";
officeNum = "?";
}
public Instructor(String first, String last, String office)
{
this.setFirstName(first);
this.setLastName(last);
this.setOfficeNum(office);
}
public Instructor(Instructor inst)
{
firstName = inst.firstName;
lastName = inst.lastName;
officeNum = inst.officeNum;
}
//----------------------------------------------------------------------
// ACCESSORS
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public String getOfficeNum()
{
return officeNum;
}
//----------------------------------------------------------------------
//METHODS
public void setFirstName(String someFirstName)
{
this.firstName = someFirstName;
}
public void setLastName(String someLastName)
{
this.lastName = someLastName;
}
public void setOfficeNum(String someOffice)
{
this.officeNum = someOffice;
}
public String toString()
{
return ("\nLast Name:\t" + lastName +
"\nFirst Name:\t " + firstName +
"\nOffice Number:\t" + officeNum);
}
}
And finally heres the output:
> Choice Action
------ ------
A Add Course
D Display Course
Q Quit
? Display Help
What action would you like to perform?
A
Please enter the Instructor information:
Enter instructor's first name: John
Enter instructor's last name: Appleseed
Enter instructor's office number: 501
Please enter the Course information:
Enter course name: Intro to Java
Enter university name: ASU
What action would you like to perform?
D
Course name: Intro to Java at ASU
Instructor Information:null
What action would you like to perform?
Instead of Information:null, it should be printing out:
Last name: Appleseed
First name: John
Office Number: 501
How can I fix this?
Thanks!
You've never set the instructor property inside Course, after it is initialized as null. You should not use static fields in Instructor. You should create a new Instructor() and assign the instructor instance to the instructor property of Course
First fix your Instructor class:
public class Instructor
{
/******These should not be public static********/
private String firstName;
private String lastName;
private String officeNum;
...
}
Next fix your Course class
public class Course
{
private String courseName;
private Instructor instructor;
private String university;
public Course(String name, Instructor inst, String univer)
{
this.setName(name);
this.setInstructor(inst);
this.setUniversity(univer);
}
public void setInstructor(Instructor inst)
{
this.instructor = inst;
}
...
}

How can I use a string attribute of a class to refer to that class in java?

I have the following 3 classes that is meant to represent a program that allows a user to create a sort of database that can add people and their phone numbers and addresses and then search for them once created.
Here are the classes:
Person
import java.util.*;
public class Person implements Comparable<Person> {
private final String name;
private String street;
private String city;
private String address;
public Person(String name) {
this.name = name;
this.address = "address unknown";
}
public String getName() {
return name;
}
public void setAddress(String street, String city){
this.city = city;
this.street = street;
this.address = this.street + " " + this.city;
}
public String getAddress() {
return address;
}
#Override
public int compareTo(Person o) {
return this.name.compareToIgnoreCase(o.getName());
}
}
PhoneNumbers (to store the person + their phone numbers)
import java.util.*;
import java.util.Collections;
public class PhoneNumbers {
private Map<Person, Set<String>> numbers;
public PhoneNumbers() {
this.numbers = new HashMap<Person, Set<String>>();
}
public void addPhoneNumber(Person person, String phoneNumber){
if(!this.numbers.keySet().contains(person)){
this.numbers.put(person, new HashSet<String>());
}
this.numbers.get(person).add(phoneNumber);
}
public Set<String> searchByPerson(Person person){
if(!this.numbers.keySet().contains(person)){
return this.numbers.get(person);
}
return null;
}
public String searchByNumber(String number){
for(Person person : this.numbers.keySet()){
Set<String> x = this.numbers.get(person);
for(String y : x){
if(y.equals(number)){
return person.getName();
}
}
}
return " not found";
}
public void personalSearch(Person person){
System.out.println(" " + person.getAddress());
if(this.numbers.get(person).size() == 0){
System.out.println(" phone number not found");
}
for(String x : this.numbers.get(person)){
System.out.println(" phone numbers");
System.out.println(" " + x);
}
}
public void remove(Person person){
this.numbers.remove(person);
}
public List<Person> masterSearch(String search){
ArrayList<Person> names = new ArrayList<Person>();
for(Person person : this.numbers.keySet()){
if(person.getName().contains(search) || person.getAddress().contains(search)){
names.add(person);
}
}
Collections.sort(names);
return names;
}
public Map<Person, Set<String>> getNumbers() {
return numbers;
}
}
UI (to provide the way for the user to interact with the program)
import java.util.Scanner;
public class UI {
private Scanner reader;
private PhoneNumbers phoneNumbers;
public UI() {
this.reader = new Scanner(System.in);
this.phoneNumbers = new PhoneNumbers();
}
public void start(){
System.out.println("phone search\n" +
"available operations:\n" +
" 1 add a number\n" +
" 2 search for a number\n" +
" 3 search for a person by phone number\n" +
" 4 add an address\n" +
" 5 search for personal information\n" +
" 6 delete personal information\n" +
" 7 filtered listing\n" +
" x quit\n");
while(true){
System.out.print("command: ");
int command = Integer.parseInt(reader.nextLine());
System.out.println("");
if(command == 1){
System.out.print("whose number: ");
String name = reader.nextLine();
System.out.print("number: ");
String number = reader.nextLine();
Person person = new Person(name);
this.phoneNumbers.addPhoneNumber(person, number);
}
else if(command == 2){
System.out.print("whose number: ");
String person = reader.nextLine();
//something here
}
}
else{
System.out.println(" not found");
}
}
}
}
}
I have a question with the code in the UI specifically
else if(command == 2){
System.out.print("whose number: ");
String person = reader.nextLine();
when the command is given as 2 I ask the user for a name and that is given as a string, how do I then use that String to find the value of the person object with that name under the HashMap i.e. the set of numbers associated with the person.
Obviously I cannot do this with a get method on the map as the keys are person objects not strings and I don't know what to do (do I need to store a map between String name and Person name), I believe in this context names are unique?
Also bonus question: why would I be getting an error when I do command 1 and give a number that is not all digits like "045-4558" for instance.
Thank you
Maybe something like that:
for (Map.Entry<Person, Set<String>> entry : numbers.entrySet()) {
Person key = entry.getKey();
if (key.getName().equals(nameWhichYouAreLookingFor)) {
//Do whatever you want
}
}

How to finish this Java classes assignment?

Here is my assignment:
Create a class that contains an address book entry and name it AddressBook. The table below describes the information that an address book entry has. Name, Address, Mobile Number, Email Address.
Here is my code, I am not sure if it's correct:
public class AddressBook {
private String name;
private String address;
private int mobilenumber;
private String emailaddress;
public AddressBook(){}
public AddressBook (String name, String address,
int mobilenumber, String emailaddress){
this.name = name;
this.address = address;
this.mobilenumber = mobilenumber;
this.emailaddress = emailaddress;
}
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 int getMobileNumber(){
return mobilenumber;
}
public void setMobileNumber(int mobilenumber){
this.mobilenumber = mobilenumber;}
public String getEmailAddress(){
return emailaddress;
}
public void setEmailAddress(String emailaddress){
this.emailaddress = emailaddress;
}
public String toString(){
return "Name: " + name + "Address: " + address +
"Mobile Number: " + mobilenumber + "Email Address: " + emailaddress;
}
}
Here is the next part of the assignment:
Create a class and name it AddressBookTest which will contain the main method for implementation of the AddressBook class methods from #1 of this activity. Instantiate an array of AddressBook objects of 100 entries. Create a menu that will implement the following methods:
Main Menu
Add Entry
Delete Entry
View All Entries
Update An Entry
Exit
The program should loop back to the main menu after implementing a method chosen by the user. Note that options 2, 3 and 4 should not be implemented if no entry has been added yet. The program ends at the Exit option.
Here my current code, I don't know how to delete, view all or update?
import java.util.Scanner;
public class AddressBookTest {
public static void main(String[] args) {
System.out.println("***PROGRAM INFORMATION*** \nNAME
-> IS THE NAME OF THE PERSON IN THE ADDRESSBOOK \nADDRESS
-> THE ADDRESS OF THE PERSON \nMOBILE NUMBER
-> THE MOBILE NUMBER OF THE PERSON \nEMAIL ADDRESS
-> THE EMAIL ADDRESS OF THE PERSON\n");
String input;
Scanner in = new Scanner(System.in);
AddressBook[] entry = new AddressBook[100];
do
{
System.out.println("Main Menu");
System.out.println("1. Add an Entry");
System.out.println("2. Delete an Entry");
System.out.println("3. View All Entries");
System.out.println("4. Update an Entry");
System.out.println("5. Exit");
System.out.print("Please enter Choices from 1 to 5: ");
input =(in.nextLine());
switch (input) {
case "1":
for(int i = 0; i < 100; i++){
entry[i] = new AddressBook();
System.out.println("***Adding Entry in Address Book***");
System.out.print("First Name: ");
String name = in.next();
System.out.print("Address: ");
String address = in.next();
System.out.print("Mobile Number: ");
int MN = in.nextInt();
System.out.print("Email Address: ");
String EA = in.next();
System.out.println("***Added " + (i+1) + " Entry/Entries\n");
}
break;
case "2":
break;
case "3":
break;
case "4":
break;
default:
break;
}
}while(!input.equals("5"));
System.out.println("***THANK YOU FOR USING MY PROGRAM...***");
}
}
Hopefully this answer helps you with your question:
Here my current code, I don't know how to delete, view all or update?
I really tried to keep it basic, the only new thing introduced is the list instead of an array.
Well first things first, like already said by #daniu. We'll need to change AddressBook to AddressBookEntry, because it really is an entry, not an address book.
AddressBookEntry.java:
package com.kaufland;
//class like it was given
public class AddressBookEntry {
private String name;
private String address;
private int mobilenumber;
private String emailaddress;
public AddressBookEntry() {}
public AddressBookEntry(String name, String address,
int mobilenumber, String emailaddress){
this.name = name;
this.address = address;
this.mobilenumber = mobilenumber;
this.emailaddress = emailaddress;
}
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 int getMobileNumber(){
return mobilenumber;
}
public void setMobileNumber(int mobilenumber){
this.mobilenumber = mobilenumber;}
public String getEmailAddress(){
return emailaddress;
}
public void setEmailAddress(String emailaddress){
this.emailaddress = emailaddress;
}
public String toString(){
return "Name: " + name + ", Address: " + address +
", Mobile Number: " + mobilenumber + ", Email Address: " + emailaddress;
}
}
Second we need class which represents our AddressBook and contains a List of AddressBookEntries. We chose a List here, because it is easy to extend, which a AdressBook should be.
AdressBook.java:
package com.kaufland;
import java.util.ArrayList;
import java.util.List;
public class AddressBook {
//The diamond operators "<" and ">" specify which type of Objects the List will hold
private List<AddressBookEntry> listOfEntries;
public AddressBook() {
//initialize list of entries
this.listOfEntries = new ArrayList<>();
}
public void add(AddressBookEntry addressBookEntry) {
//List.add adds a new Object to a List
this.listOfEntries.add(addressBookEntry);
}
public void delete(int index) {
//List.remove(int index) removes a object at the given index
this.listOfEntries.remove(index);
}
public AddressBookEntry get(int index) {
//List.get(int index) returns the object at the given index
return this.listOfEntries.get(index);
}
public AddressBookEntry[] viewAll() {
//create a new array with the size of our list
AddressBookEntry[] result = new AddressBookEntry[this.listOfEntries.size()];
//List.toArray(Arr[] array) fills our array with data from the list
this.listOfEntries.toArray(result);
//return the filled array
return result;
}
}
Last we need to apply some changes to your AddressBookTest class, so that we use the functions of our new created AddressBook!
AddressBookTest.java:
package com.kaufland;
import java.util.Scanner;
public class AddressBookTest {
public static void main(String[] args) {
System.out.println("***PROGRAM INFORMATION*** \nNAME" +
"-> IS THE NAME OF THE PERSON IN THE ADDRESSBOOK \nADDRESS" +
"-> THE ADDRESS OF THE PERSON \nMOBILE NUMBER" +
"-> THE MOBILE NUMBER OF THE PERSON \nEMAIL ADDRESS" +
"-> THE EMAIL ADDRESS OF THE PERSON\n");
String input;
Scanner in = new Scanner(System.in);
AddressBook addressBook = new AddressBook();
boolean stop = false;
do
{
System.out.println("\nMain Menu");
System.out.println("1. Add an Entry");
System.out.println("2. Delete an Entry");
System.out.println("3. View All Entries");
System.out.println("4. Update an Entry");
System.out.println("5. Exit");
System.out.print("Please enter Choices from 1 to 5: \n");
input =(in.next());
switch (input) {
case "1":
//create a new entry for the addressbook
AddressBookEntry entry = new AddressBookEntry();
System.out.println("***Adding Entry in Address Book***");
System.out.print("First Name: ");
entry.setName(in.next());
System.out.print("Address: ");
entry.setAddress(in.next());
System.out.print("Mobile Number: ");
entry.setMobileNumber(in.nextInt());
System.out.print("Email Address: ");
entry.setEmailAddress(in.next());
//add our new entry to the addressbook
addressBook.add(entry);
System.out.println("Added a new entry.");
break;
case "2":
System.out.println("Enter the index of the entry, which you want to delete:");
//delete the entry at the given index
addressBook.delete(in.nextInt());
break;
case "3":
System.out.println("Your addressbook contains the following entries:");
//get array of all entries
AddressBookEntry[] listOfEntries = addressBook.viewAll();
//for every entry in the array
for (int i = 0; i < listOfEntries.length; i++) {
System.out.println(listOfEntries[i].toString());
}
break;
case "4":
System.out.println("Enter the index of the entry, which you want to update:");
//get entry at the given index
AddressBookEntry entryToUpdate = addressBook.get(in.nextInt());
System.out.print("First Name (current: " + entryToUpdate.getName() + "):");
entryToUpdate.setName(in.next());
System.out.print("Address: (current: " + entryToUpdate.getAddress() + "):");
entryToUpdate.setAddress(in.next());
System.out.print("Mobile Number: (current: " + entryToUpdate.getMobileNumber() + "):");
entryToUpdate.setMobileNumber(in.nextInt());
System.out.print("Email Address: (current: " + entryToUpdate.getEmailAddress() + "):");
entryToUpdate.setEmailAddress(in.next());
break;
default:
break;
}
//execute while stop is false
} while (!input.equals("5"));
System.out.println("***THANK YOU FOR USING MY PROGRAM...***");
}
}

How to create an arraylist using polymorphism?

I am trying to create an array list that contains all employees and is able to handle any type of employee. I also have to load the data onto to the list The class I'm using is called payroll. This is what I have so far:
The employee class looks like this:
import java.util.*;
public abstract class Employee
{
private String name, employeeNum, department;
private char type;
public Employee()
{
name ="";
employeeNum = "";
department = "";
}
public Employee(String Name, String EmpNum, String Depart)
{
name = Name;
employeeNum = EmpNum;
department = Depart;
}
//public EMpoy
public String getName()
{
return name;
}
public String getEmployeeNum()
{
return employeeNum;
}
public String getDepartment()
{
return department;
}
public char getType()
{
return type;
}
public void setName(String Name)
{
name = Name;
}
public void setEmployeeNum(String EmpNum)
{
employeeNum = EmpNum;
}
public void setDepartment(String Depart)
{
department = Depart;
}
public String toString()
{
String str;
str = "Employee Name: " + name + "\n"
+ "Employee Number: " + employeeNum + "\n"
+ "Employee Department: " + department + "\n";
return str;
}
}
The payroll class looks like this so far:
import java.util.*;
import java.io.*;
public class Payroll
{
private ArrayList<Employee> list = new ArrayList<Employee>();
private String fileName;
public Payroll()
{
}
public void fileName(String[] args)
{
Scanner kb = new Scanner(System.in);
System.out.println("InsertFileName");
String fileName1 = kb.next();
fileName = fileName1 + ".txt";
}
public void loadData() throws FileNotFoundException
{
Scanner s = new Scanner(new File(fileName));
while (s.hasNext())
{
String name = s.next();
String employeeNum = s.next();
String department = s.next();
//String typeString = s.next();
//char type = typeString.toUpperCase().charAt(0);
char type = s.next().toUpperCase().charAt(0);
if (type == 'S')
{
double yearlySalary = s.nextDouble();
list.add(new Salary (name, employeeNum, department, yearlySalary));
}
else if (type == 'H')
{
double hourlyPayRate = s.nextDouble();
String hours = s.next();
int hoursWorked = Integer.parseInt(hours);
list.add(new Hourly (name, employeeNum, department, hourlyPayRate, hoursWorked));
}
else if (type == 'C')
{
int numOfWeeks = s.nextInt();
double baseWeeklySalary = s.nextDouble();
int salesThisWeek = s.nextInt();
int salesThisYear = s.nextInt();
double commissionRate = s.nextDouble();
list.add(new Commission (name, employeeNum, department, numOfWeeks, baseWeeklySalary, salesThisWeek, salesThisYear, commissionRate));
}
}
s.close();
}
Now I know I'm supposed to make the arraylist in the constructor, that's what I'm having trouble with. How can I make the list using polymorphism to get every employee? Thanks.
Hi Srk93 You are getting error as your list contains the references of Employee class and Employee class does't have getCommissionRate method. You can call on Employee reference which are declared in Employee class. Create abstact method of calculateSalary() and implement in all your child classes.
Its duplicate of "cannot find symbol: method" but the method is declared

Categories