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

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;
}
...
}

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

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

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.

I have a text file but I only need to print certain aspects of the file

I have a text file that essentially resembles a student transcript but I only need to print the student, numbers of courses and then the courses in the this format:
Student A: # of courses
Course title 1
Course title 2
etc.
Student B: # of courses
Course title 1
Course title 2
etc.
Student C: # of courses
Course title 1
Course title 2
etc.
This is a portion of the text file:
Student A,Grade,Credit
Computer Applications,A,1
Career Investigations Phase I,A,1
English 9,A,1
World History II,A,1
Earth Science,A,1
Spanish I,A,1
Art I,A,1
Health & PE 9,B,1
Computer Information Systems,A,1
English 10 Honors,A,1
Geometry,B,1
World History I,A,1
Biology,A,1
Spanish II,A,1
Art II,A,1
Health & PE 10,B,1
"Design, Multimedia, and Web Technologies",C,1
Virginia & United States History,A,1
Algebra II,A,1
Chemistry I,A,1
Spanish III,A,1
Entrepreneurship Education,A,1
Advanced Entrepreneurship Education,A,1
Honors English 12,A,1
Economics and Personal Finance,A,1
AP English Language and Composition,A,1
AP Government and Politics: US,A,1
Mathematical Analysis/Pre-Calculus,A,1
Physics I,A,1
Introduction to Fashion Careers,A,1
Introduction to Culinary Arts,A,1
Career Interpretation - Phase II,A,1
My code so far just print the entire file. I've tried using system.out.println()
in the other places but nothing works. This is my code currently.
import java.io.*;
import java.util.*;
import java.util.Scanner;
public class Phase1 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException {
// TODO code application logic here
Scanner file = new Scanner(new
FileReader("C:\\Users\\coderva.org\\Downloads\\FakeData.csv"));
ArrayList<Student> students = new ArrayList<Student>();
while(file.hasNextLine())
{
String line = file.nextLine();
String[] lines = line.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
System.out.println(line);
}
}
class Course
{
private char grade;
private double credit;
private String title;
public Course()
{
title = "";
grade = 'I';
credit = 0;
}
public Course(String title, char grade, double credit)
{
this.title= title;
this.grade = grade;
this.credit = credit;
}
public String getTitle()
{
return title;
}
public char getGrade()
{
return grade;
}
public double getCredit()
{
return credit;
}
public String toString()
{
return title + " " + grade + " " + credit;
}
}
class Student
{
private String name;
private ArrayList<Course> courses;
public Student()
{
name = null;
courses = null;
}
public Student(String name, ArrayList<Course> courses)
{
this.name = name;
this.courses = courses;
}
public void setName(String name)
{
this.name = name;
}
public void setCourses(ArrayList<Course> courses)
{
this.courses = courses;
}
public String getName()
{
return name;
}
public ArrayList<Course> getCourses()
{
return courses;
}
}
}
Okay, so in your code, you created a main class called Phase1, a course class called Course, and a student class called Student. The idea behind creating these classes is correct. Basically, in your main class, you want to run through each line of the input file and parse the contents. You need to determine if the line of the input file is a new student or a course that will be added to the current student. If the line contains a new student, you need to create a new student object using your Student class. Otherwise, you need to add a new course, using your course class, to add to a student's list of classes. Once you have parsed the whole file, you can then loop through the list of students and the list of courses that each student has.
Phase1 Class:
import java.io.*;
import java.util.*;
import java.util.Scanner;
public class Phase1 {
public static void main(String[] args) throws FileNotFoundException {
Scanner file = new Scanner(new FileReader("data.txt"));
ArrayList<Student> students = new ArrayList<Student>();
int currStudent = -1;
while(file.hasNextLine()) {
String line = file.nextLine();
String[] split = new String[3];
//Parse the line input, check if a course name has a comma (it has a comma if it is in quotation marks), otherwise proceed normally
if(line.indexOf('"') == -1) {
split = line.split(",");
} else {
split[0] = line.substring(line.indexOf('"')+1, line.lastIndexOf('"'));
split[1] = line.substring(line.lastIndexOf('"')+2, line.lastIndexOf(','));
split[2] = line.substring(line.lastIndexOf(',')+1,line.length());
}
//If the line contains a new student, create the student
if(split[0].contains("Student")) {
students.add(new Student(split[0],new ArrayList<Course>()));
currStudent++;
continue;
}
//Add course to the current student
students.get(currStudent).addCourse(split[0], split[1].charAt(0), Double.parseDouble(split[2]));
}
//Print all students
for(Student s : students) {
System.out.println(s.getName() + ": " + s.getCourses().size());
//Print all courses for each student
for(Course c : s.getCourses()) {
System.out.println(c.getTitle());
}
System.out.println();
}
file.close();
}
}
Course Class (Same as yours above):
public class Course
{
private char grade;
private double credit;
private String title;
public Course() {
title = "";
grade = 'I';
credit = 0;
}
public Course(String title, char grade, double credit) {
this.title= title;
this.grade = grade;
this.credit = credit;
}
public String getTitle() {
return title;
}
public char getGrade() {
return grade;
}
public double getCredit() {
return credit;
}
public String toString() {
return title + " " + grade + " " + credit;
}
}
Student Class (Slightly modified - Changed setCourses to addCourse):
import java.util.*;
public class Student {
private String name;
private ArrayList<Course> courses;
public Student() {
name = null;
courses = null;
}
public Student(String name, ArrayList<Course> courses) {
this.name = name;
this.courses = courses;
}
public void setName(String name) {
this.name = name;
}
public void addCourse(String title, char grade, double credit) {
this.courses.add(new Course(title,grade,credit));
}
public String getName() {
return name;
}
public ArrayList<Course> getCourses() {
return courses;
}
}
Let me know if you have any questions about understanding the code!

Error when trying to add user input to an array

I am quite new to java and am having a problem trying to store user input to an array to later be able to call the list, however I am getting an error when trying to do so. The error comes on the newvoter.add(); line. Sorry if I'm being ignorant in any way, I feel like I'm being stupid!
public class admin {
public static Scanner sc = new Scanner (System.in);
public static List<voter> Voters = new ArrayList<voter>();
public static int promptUserInput() {
System.out.print("\n\tEnter: ");
int option = sc.nextInt();
return option;
}
public static int getOption() {
int option = promptUserInput();
switch(option){
case 1:
addVoter();
break;
case 2:
//deleteVoter();
break;
case 3:
Questions openQuestions = new Questions();
openQuestions.addQuestion();
break;
case 4:
break;
case 5:
System.out.println("Programme Ended");
System.exit(0);
default:
break;
}
return option;
}
public static void main(String[] args) {
printMenu();
}
public static void printMenu(){
System.out.println("\nAdmin Options Menu\n"
+ "\t\nPlease enter an option:\t\n"
+ "\n\t\t1: Create Voter\t\n"
+ "\t\t2:Delete Voter\t\n"
+ "\t\t3:Add Questions\t\n"
+ "\t\t4: View Questions List\t\n"
+ "\t\t5: Delete Question\t\n");
getOption();
}
private static void addVoter(){
voterAdd newvoter = new voterAdd(); // Creates a new voter
System.out.println("Enter First Name: ");
String firstName = sc.next();
System.out.println("Enter Surname Name: ");
String surname = sc.next();
System.out.println("Enter Voter ID: ");
int voterID = sc.nextInt();
System.out.println("Enter City: ");
String city = sc.next();
newvoter.setVoter(firstName, surname, voterID, city);//calls the 'setVoter' method inherited from 'voter'
newvoter.add();//adds the 'newVoter' to the ArrayList 'voter'
System.out.println("\n New voter identification has been created and stored.\n");
listVoters();
}
Here is the class it calls from..
public class voterAdd {
private String firstName = "";
private String surname = "";
private int voterID = 0; //voterID of the voter
private String city = "";
public void setVoter(String firstName, String surname, int voterID, String city) {
this.firstName = firstName;
this.surname = surname;
this.voterID = voterID;
this.city = city;
}
public String getFirstName()
{
return firstName;
}
public String getsurname()
{
return surname;
}
public int getID()
{
return voterID;
}
public String getCity()
{
return city;
}
}
It's Voters.add(newvoter);, not newvoter.add(). Also, variable names should start with a lowercase letter or an underscore. Classes should start with uppercases.
Well one of your problems is that you are calling in your List the voter class, when maybe it should be the voteradd class like such:
List<voteradd> listName = new List<voteradd>();
Another thing, common java principles expect java classes to start with a capital letter(camel case), it's just good conventions and good practice. Hopefully this helped, best of luck :)

Creating a contact list with java and object oriented

I am new to programming and object oriented design. This is my last requirement to finish my bachelors degree (not in programming). I am so confused with how to make object oriented work, and nothing I look at seems to help.
The assignment is to create a contact list that uses inheritance, polymorphism,and collections. I need a contact list that is stores two types of contacts: business and personal.
1. Prompt to select which contact to add or display.
2. Prompt to allow user to enter the contact info.
3. Prompt that will display the output of a chosen contact back.
I have the following class and subclasses. I am stuck on how I am supposed to read in the inputs to the specific arraylists. I don't even know if the classes are built right either.
Any help would be awesome, I just need to get through this, then I will gladly leave programing to those that know what they are doing.
This is what I have for my Parent Class:
package ooo1;
public abstract class Contact {
private String contactId;
private String firstName;
private String lastName;
private String address;
private String phoneNumber;
private String emailAddress;
public Contact(String contactId,String firstName,String lastName, String address, String phoneNumber, String emailAddress)
{
this.contactId = contactId;
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.phoneNumber = phoneNumber;
this.emailAddress = emailAddress;
}
public void setContactId(String input){
this.contactId = input;
}
public String getContactId(){
return contactId;
}
public void setFirstName(String input){
this.firstName = input;
}
public String getFirstName(){
return firstName;
}
public void setLastName(String input){
this.lastName = input;
}
public String getLastName(){
return lastName;
}
public void setAddress(String input){
this.address = input;
}
public String getAddress(){
return address;
}
public void setPhoneNumber(String input){
this.phoneNumber = input;
}
public String getPhoneNumber(){
return phoneNumber;
}
public void setEmailAddress(String input){
this.emailAddress = input;
}
public String getEmailAddress(){
return emailAddress;
}
void displayContact(){
System.out.println("Contact ID:" + contactId + " First Name:" + firstName + " Last Name:" + lastName);
System.out.println("Address:" + address);
System.out.println("Phone Number:" + phoneNumber);
System.out.println("Email Address:" + emailAddress);
}
}
This is one of my subclasses:
package ooo1;
public class PersonalContact extends Contact {
private String dateofBirth;
public PersonalContact(String contactId, String firstName, String lastName, String address, String phoneNumber, String emailAddress, String dateofBirth){
super(contactId, firstName, lastName, address, phoneNumber, emailAddress);
this.dateofBirth = dateofBirth;
}
public void setDateofBirth(String input){
this.dateofBirth=input;
}
public String getDateofBirth(){
return this.dateofBirth;
}
}
This is my other subclass:
package ooo1;
public class BusinessContact extends Contact {
private String jobTitle;
private String organization;
public BusinessContact(String contactId, String firstName, String lastName, String address, String phoneNumber, String emailAddress, String jobTitle, String organization){
super(contactId, firstName, lastName, address, phoneNumber, emailAddress);
this.jobTitle = jobTitle;
this.organization = organization;
}
public void setJobTitle(String input){
this.jobTitle = input;
}
public String getJobTitle(){
return this.jobTitle;
}
public void setOrganization(String input){
this.organization = input;
}
public String getOrganization(){
return this.organization;
}
}
This is what I have for Main which is so wrong at this point I believe:
package ooo1;
import java.util.ArrayList;
import java.util.Scanner;
public class ContactList {
public static void main(String[] args) {
ArrayList<PersonalContact> personalList = new ArrayList<PersonalContact>();
Scanner input = new Scanner(System.in);
System.out.println("Please enter ContactId : ");
String contactId = input.nextLine();
System.out.println("Please enter First Name : ");
String firstName = input.nextLine();
System.out.println("Please enter Last Name : ");
String lastName = input.nextLine();
System.out.println("Please enter Address : ");
String address = input.nextLine();
System.out.println("Please enter Phone Number : ");
String phoneNumber = input.nextLine();
System.out.println("Please enter Email Address : ");
String emailAddress = input.nextLine();
System.out.println("Please enter Birthday: ");
String dateofBirth = input.nextLine();
}
}
You have the pieces in place you just need to put them together. First, think about the List being used. It is supposed to hold both types of contacts, however its type argument is using the derived type PersonalContact. Instead use the base class Contact
List<Contact> contacts = new ArrayList<Contact>();
Next it appears you start to gather the information about the contact from the end user via the console. Before doing this you may want to ask what type of contact is being entered, maybe give the option to enter 1 for a personal contact or 2 for a business contact. Then collect the information specific to the type of contact they chose.
Scanner input = new Scanner(System.in);
System.out.println("Please enter Specify the contact type (1 Personal, 2 Business) : ");
int contactType = input.nextInt();
//collect data common to both types
if(contactType == 1){
//collect information specific to personal
} else if(contactType ==2){
//collect information specific to business
}
Next you need to turn the data you collected into the actual objects, using a the constructors. This will need to be done conditionally and could actually be a part of the last section if done properly.
Contact contact;
if(contactType == 1){
contact = new PersonalContact(/*arguments here*/);
} else{
contact = new BusinessContact(/*arguments here*/);
}
Then finish up by adding the contact to your list:
contacts.add(contact);
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaprac;
/**
*
* #author Arijit
*/
public class Contact {
private String name;
private int number;
public Contact(int number,String name) {
this.name = name;
this.number = number;
}
public String getName() {
return name;
}
public int getNumber() {
return number;
}
public static Contact createContact(int number, String name){
return new Contact(number,name);
}
}
This is the Contact class, which is governed by a contact name and a contact number. Next we will design the MobilePhone class which will have a number(optional) and an arraylist of contacts.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaprac;
import java.util.ArrayList;
/**
*
* #author Arijit
*/
class MobilePhone1 {
public int mynumber;
public ArrayList < Contact > contacts;
public MobilePhone1(int mynumber) {
this.mynumber = mynumber;
this.contacts = new ArrayList < Contact > ();
}
public Boolean addContact(Contact contact) {
if (findPosition(contact) >= 0) {
System.out.println("Contact already is phone");
return false;
} else {
contacts.add(contact);
}
return true;
}
public ArrayList < Contact > getContacts() {
return contacts;
}
public void updateContact(Contact oldContact, Contact newContact) {
if (findPosition(oldContact) >= 0) {
contacts.set(findPosition(oldContact), newContact);
} else {
System.out.println("Contact does not exist");
}
}
public void removeContact(Contact contact) {
if (findPosition(contact) >= 0) {
contacts.remove(findPosition(contact));
} else {
System.out.println("No contact");
}
}
public int searchContact(Contact contact) {
int position = findPosition(contact);
if (contacts.contains(contact)) {
System.out.println("Item found at position");
return position;
}
System.out.println("Not found");
return -1;
}
private int findPosition(Contact contact) {
return this.contacts.indexOf(contact);
}
private int findPosition(String name) {
for (int i = 0; i < contacts.size(); i++) {
Contact contact = this.contacts.get(i);
if (contact.getName().equals(name)) {
return i;
}
}
return -1;
}
}
public class MobilePhone {
public static void main(String args[]) {
Boolean quit = false;
int choice = 0;
java.util.Scanner sc = new java.util.Scanner(System.in);
MobilePhone1 phone = new MobilePhone1(98312);
//Contact newcontact = Contact.createContact(12345,"Arijt");
while (!quit) {
System.out.println("Enter your choice");
choice = sc.nextInt();
sc.nextLine();
switch (choice) {
case 0:
System.out.println("Enter the number of Contacts");
int count = sc.nextInt();
for (int i = 0; i < count; i++) {
System.out.println("Enter number");
int phoneNumber = sc.nextInt();
System.out.println("Enter Name");
sc.nextLine();
String name = sc.nextLine();
Contact newcontact = Contact.createContact(phoneNumber, name);
phone.addContact(newcontact);
}
break;
case 1:
int size = phone.getContacts().size();
System.out.println(size);
for (int i = size - 1; i >= 0; i--) {
phone.removeContact(phone.getContacts().get(i));
}
System.out.println(phone.getContacts().isEmpty());
break;
case 2:
for (int i = 0; i < phone.getContacts().size(); i++) {
System.out.println(phone.searchContact(phone.getContacts().get(i)));
}
break;
case 3:
//Contact newcontact1 = Contact.createContact(12345,"Buzz");
System.out.println("Enter the Contact name you want to update");
String oldContactName = sc.nextLine();
for (int j = 0; j < phone.getContacts().size(); j++) {
if (phone.getContacts().get(j).getName().equals(oldContactName)) {
System.out.println("Enter the new Contact name");
String newName = sc.nextLine();
System.out.println("Enter the new Contact number");
int newNumber = sc.nextInt();
phone.updateContact(phone.getContacts().get(j), Contact.createContact(newNumber, newName));
} else {
System.out.println("You are looking for the wrong contact");
}
}
for (int i = 0; i < phone.getContacts().size(); i++) {
System.out.println(phone.getContacts().get(i).getName() + "," + phone.getContacts().get(i).getNumber());
}
break;
case 4:
if(phone.getContacts().isEmpty()){
System.out.println("Emtpty contact list");
}
else {
System.out.println("Contact list");
for (int i = 0; i < phone.getContacts().size(); i++) {
System.out.println("Name: "+phone.getContacts().get(i).getName() + ",Phone Number: " + phone.getContacts().get(i).getNumber());
}
}
break;
case 6:
System.out.println("Enter 0 for adding contact\n");
System.out.println("Enter 1 for removing every contact\n");
System.out.println("Enter 2 for searching contact\n");
System.out.println("Enter 3 for updating contact\n");
System.out.println("Enter 4 for viewing the contact list\n");
System.out.println("Enter 6 for exiting\n");
System.out.println("Enter 5 to see the instrusctions again\n");
break;
case 5:
quit = true;
break;
}
}
}
}

Categories