Edit and Update ArrayList in Java - java

I am trying to update myArray list by allowing the user to change their first and last name while keeping other information in the arraylist the same.
the code follows
public void editStudentID(int findStudentId) {
for (int i = 0; i < students.size(); i++) {
if (students.get(i).getId() != findStudentId) {
continue;
}
System.out.println("Found a profile containing information for " + findStudentId + ":");
System.out.println("What would you like to change in your profile?");
System.out.println("1.First Name");
System.out.println("2.Last Name");
int decision = scanner.nextInt();
switch (decision) {
case 1:
System.out.println("Enter a new first name to continue");
String newFirstName = scanner.next();//need to find a way to update this in my arraylist
break;
case 2:
System.out.println("Enter a new last name to continue");
String newLastName = scanner.next();//this as well
break;
}
return;
}
System.out.println(" Id not found ");
}
this is my Student class where I only wrote final for only my id and dob to not be changed by the user
public class Student {
private final int id;
private String firstName;
private String lastName;
private final String dob;
public Student(int id, String firstName, String lastName, String dob) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.dob = dob;
}
public int getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getDob() {
return dob;
}
public static Student createStudentID(int id, String firstName, String lastName, String dob) {
return new Student(id, firstName, lastName, dob);
}
}

First, you need to make you Student class mutable, but supplying a couple of "setters" which will allow you to change the first and last name properties, for example
public class Student {
//...
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Then in you editStudentID method, you simply update the required record, for example
public void editStudentID(int findStudentId) {
for (int i = 0; i < students.size(); i++) {
if (students.get(i).getId() != findStudentId) {
continue;
}
System.out.println("Found a profile containing information for " + findStudentId + ":");
System.out.println("What would you like to change in your profile?");
System.out.println("1.First Name");
System.out.println("2.Last Name");
int decision = scanner.nextInt();
switch (decision) {
case 1:
System.out.println("Enter a new first name to continue");
String newFirstName = scanner.next();//need to find a way to update this in my arraylist
students.get(i).setFirstName(newFirstName);
break;
case 2:
System.out.println("Enter a new last name to continue");
String newLastName = scanner.next();//this as well
students.get(i).setLastName(newFirstName);
break;
}
return;
}
System.out.println(" Id not found ");
}

Related

Using an arrayList to create a menu and using a text file as input(bufferedReader)

As you can see below I tried creating a switch case for choices
1. Name
2. Course then Name
3. Year Level then Name
4. Course then Year Level and the Name
5. Exit
I don't know how to use switch case so that I could sort everything according to the menu. I will be using comparable and I am only allowed to edit the method called compareTo. My mind is blank and I got no idea where to start.
20192215
Ang
Bryan
m
BSCS
4
20192200
Santos
Charlie
m
BSIT
2
20192452
Chua
Leah
f
BSIS
4
20190012
Yee
John
m
BSCS
2
These are the inputs from text file
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;
import java.util.Vector;
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
try {
BufferedReader br = new BufferedReader(new FileReader("c://student.txt"));
char g;
int yl, I;
String ln, fn, id, cors, con;
Student v[] = new Student[4];
Scanner sc= new Scanner(System.in);
boolean en = true;
boolean ent = true;
for(i = 0; i < 4; i++){
id = br.readLine();
ln = br.readLine();
fn = br.readLine();
g = br.readLine().charAt(0);
cors = br.readLine();
yl = Integer.parseInt(br.readLine());
v[i] = new Student(ln, fn, id, cors, g, yl);
}
while(en == true){
System.out.println("--------------------------------------");
System.out.println("--------------------------------------");
System.out.println("1. Name");
System.out.println("2. Course then Name");
System.out.println("3. Year Level then Name");
System.out.println("4. Course then Year Level and the Name");
System.out.println("5. Exit");
System.out.println("--------------------------------------");
System.out.println("--------------------------------------");
System.out.println("Choose Menu: ");
int choice = sc.nextInt();
switch(choice){
case 1 :
Arrays.sort(v);
display_array(v);
break;
case 2 :
Arrays.sort(v);
display_array(v);
break;
case 3 :
Arrays.sort(v);
display_array(v);
break;
case 4 :
Arrays.sort(v);
display_array(v);
break;
case 5 :
en = false;
System.out.println("\n\n \nTHANK YOU FOR USING THE PROGRAM!!");
break;
}
if(en != false){
System.out.println("Press [Enter key] to continue");
try{
System.in.read();
}catch(Exception e){
e.printStackTrace();
}
}
}
} catch (FileNotFoundException e) {
System.err.println("File not found");
} catch (IOException e) {
System.err.println("Unable to read the file.");
}
}
public static void display_array(Student arr_v[]) throws IOException{
System.out.println("--------------------------------------");
for(int i = 0; i < arr_v.length; i++){
arr_v[i].display();
}
System.out.println("--------------------------------------");
}
}```
```
public class Student implements Comparable {
private String lastname, firstname, studentid, course;
private char gender;
private int yearlevel;
public Student(String ln, String fn, String id, String cors, char g, int yl) {
lastname = ln;
firstname = fn;
studentid = id;
course = cors;
gender = g;
yearlevel = yl;
}
public int compareTo(Object anotherObject) {
Student anotherStudent = (Student) anotherObject;
int compareResult =
this.course.compareTo(anotherStudent.lastname);
if(compare )
return 0;
}
public void display() {
System.out.printf("ID: %-8s Name: %-20s Sex: %c Course: %-8s Year: %d\n", studentid, (lastname + ", " + firstname), gender, course, yearlevel );
}
public void setGender(char gender){
this.gender = gender;
}
public char getGender(){
return gender;
}
public void setLastname(String lastname){
this.lastname = lastname;
}
public String getLastname(){
return lastname;
}
public void setFirstname(String firstname){
this.firstname = firstname;
}
public String getFirstname() {
return firstname;
}
public void setStudentId(String studentid){
this.studentid = studentid;
}
public String getStudentId(){
return studentid;
}
public void setCourse(String course){
this.course = course;
}
public String getCourse(){
return course;
}
public void setYearLevel(int yearlevel){
this.yearlevel = yearlevel;
}
public int getYearLevel(){
return yearlevel;
}
}```
public final class Student {
private final String id;
private final String firstName;
private final String lastName;
private final char gender;
private final String course;
private final int yearLevel;
public Student(String id, String firstName, String lastName, char gender, String course, int yearLevel) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.gender = Character.toUpperCase(gender);
this.course = course;
this.yearLevel = yearLevel;
}
public void display(PrintStream out) {
out.format("Name : %s, %s\n", lastName, firstName);
out.format("Student ID : %s\n", id);
out.format("Course : %s\n", course);
out.format("Gender : %s\n", gender);
out.format("Year Level : %d\n", yearLevel);
}
}
public static void main(String... args) throws FileNotFoundException {
File file = new File("c://student.txt");
List<Student> students = readStudents(file);
display(students);
}
private static List<Student> readStudents(File file) throws FileNotFoundException {
try (Scanner scan = new Scanner(file)) {
List<Student> students = new ArrayList<>();
while (scan.hasNext()) {
String id = scan.next();
String lastName = scan.next();
String firstName = scan.next();
char gender = scan.next().charAt(0);
String course = scan.next();
int yearLevel = scan.nextInt();
students.add(new Student(id, firstName, lastName, gender, course, yearLevel));
}
return students;
}
}
private static void display(List<Student> students) {
System.out.println("--------------------------------------");
System.out.println("--------------------------------------");
System.out.println("1. Name");
System.out.println("2. Course then Name");
System.out.println("3. Year Level then Name");
System.out.println("4. Course then Year Level and the Name");
System.out.println("5. Exit");
System.out.println("--------------------------------------");
System.out.println("--------------------------------------");
students.forEach(student -> {
student.display(System.out);
System.out.println();
});
}
All programmers need to learn how to debug their code. If you are using an IDE then I recommend that you learn how to use its debugger.
You have some calls to method readLine() that you do not need. In the below code, I have marked these lines as comments. I also incorporated the methods display_array() and main() into class Student just so everything would be in the one class, but you don't have to do that.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Student {
private String lastname, firstname, studentid, course;
private char gender;
private int yearlevel;
public Student(String id, String ln, String fn, char g, String cors, int yl) {
studentid = id;
lastname = ln;
firstname = fn;
gender = g;
course = cors;
yearlevel = yl;
}
private static void display_array(Student[] v) {
for (Student s : v) {
s.display();
}
}
public void display() {
System.out.println("Name : " + lastname + ", " + firstname);
System.out.println("Student ID: " + studentid);
System.out.println("Course : " + course);
System.out.println("Gender : " + gender);
System.out.println("Year Level: " + yearlevel);
}
public void setGender(char gender){
this.gender = gender;
}
public char getGender(){
return gender;
}
public void setLastname(String lastname){
this.lastname = lastname;
}
public String getLastname(){
return lastname;
}
public void setFirstname(String firstname){
this.firstname = firstname;
}
public String getFirstname() {
return firstname;
}
public void setStudentId(String studentid){
this.studentid = studentid;
}
public String getStudentId(){
return studentid;
}
public void setCourse(String course){
this.course = course;
}
public String getCourse(){
return course;
}
public void setYearLevel(int yearlevel){
this.yearlevel = yearlevel;
}
public int getYearLevel(){
return yearlevel;
}
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("c:\\student.txt"));) {
char g;
int yl;
int i;
String ln;
String fn;
String id;
String cors;
Student v[] = new Student[Integer.parseInt(br.readLine())];
// br.readLine();
for (i = 0; i < v.length; i++) {
id = br.readLine();
ln = br.readLine();
fn = br.readLine();
// g = (char) br.read();
g = br.readLine().charAt(0);
cors = br.readLine();
yl = Integer.parseInt(br.readLine());
// if ((br.readLine()) != null)
// br.readLine();
v[i] = new Student(id, ln, fn, g, cors, yl);
}
display_array(v);
}
catch (FileNotFoundException e) {
System.err.println("File not found");
}
catch (IOException e) {
System.err.println("Unable to read the file.");
}
}
}
I also changed file student.txt. According to your code, the first line of the file needs to be the number of students in the file. In the sample file in your question, there are four students.
4
20192215
Ang
Bryan
m
BSCS
4
20192200
Santos
Charlie
m
BSIT
2
20192452
Chua
Leah
f
BSIS
4
20190012
Yee
John
m
BSCS
2

Scanner requesting multiple inputs before giving final output

So I'm new to Java and am trying to pass a variable from the scanner to my getter/setter method so that depending on the number entered it'll sort the array differently.
I've got it where the list will sort; problem is my scanner repeats where you have to enter your selection in multiple times before the list shows up.
I know the problem has to do with the call "int c = assign_6.choice()". If I hard code in a number it's fine but it appears to be making multiple calls to the choice() function.
I've tried moving the function out of the main and removing the Comparable in my setter/getter file and also removing the quick sort and using Array and Collections. None of which worked.
I feel like it's probably a stupid mistake I'm making and missing it due to not knowing Java that well. Could use help in figuring this out.
Here's my output:
nter number 1,2 or 3: 1
Enter number 1,2 or 3: 1
Enter number 1,2 or 3: 1
Enter number 1,2 or 3: 1
Enter number 1,2 or 3: 1
Enter number 1,2 or 3: 1
Enter number 1,2 or 3: 1
Enter number 1,2 or 3: 1
Enter number 1,2 or 3: 1
Enter number 1,2 or 3: 1
contacts [age=20, state=Alabama, firstname=Pickles, lastname=Cattle]
contacts [age=35, state=New York, firstname=George, lastname=Constanza]
contacts [age=90, state=Florida, firstname=Adam, lastname=Tree]
contacts [age=32, state=Illinois, firstname=Mary, lastname=Upton]
contacts [age=58, state=Washington, firstname=Bob, lastname=Wiseman]
Code:
import java.util.Scanner;
public class test_6 {
public static void main(String[] args) {
Contacts[] a = {
new Contacts(32, "Illinois", "Mary", "Upton"),
new Contacts(58, "Washington", "Bob", "Wiseman"),
new Contacts(20, "Alabama", "Pickles", "Cattle"),
new Contacts(35, "New York", "George", "Constanza"),
new Contacts(90, "Florida", "Adam", "Tree"),
};
Quick.sort(a);
for (Contacts contacts:a){
System.out.println(contacts);
}
}
public static int choice() {
System.out.print("Enter number 1,2 or 3: ");
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
return i;
}
}
public class Contacts implements Comparable<Contacts>{
Integer age;
String state;
String firstname;
String lastname;
int c = test_6.choice();
public Contacts(Integer age, String state, String firstname, String lastname){
this.age = age;
this.state = state;
this.firstname = firstname;
this.lastname = lastname;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public int compareTo(Contacts contacts) {
if (c == 1){
return this.getLastname().compareTo(contacts.getLastname());
}
else if (c == 2){
return this.getState().compareTo(contacts.getState());
}
else if (c == 3){
return this.getAge().compareTo(contacts.getAge());
}
else return 0;
}
#Override
public String toString() {
return "contacts [age=" + age + ", state=" + state + ", firstname=" + firstname + ", lastname=" + lastname
+ "]";
}
}
I'm not entirely sure, you could debug, but it may be something to do with your function being assigned in the global scope. You are better to move the static function choice() to your Contacts class/object.
Then call the choice() function from inside the initializer Contacts. For example:
import java.util.Scanner;
public class test_6 {
public static void main(String[] args) {
Contacts[] a = {
new Contacts(32, "Illinois", "Mary", "Upton"),
new Contacts(58, "Washington", "Bob", "Wiseman"),
new Contacts(20, "Alabama", "Pickles", "Cattle"),
new Contacts(35, "New York", "George", "Constanza"),
new Contacts(90, "Florida", "Adam", "Tree"),
};
Quick.sort(a);
for (Contacts contacts:a){
System.out.println(contacts);
}
}
//Function Choice Moved to Contacts.choice()
}
public class Contacts implements Comparable<Contacts>{
Integer age;
String state;
String firstname;
String lastname;
int c;
public Contacts(Integer age, String state, String firstname, String lastname){
this.age = age;
this.state = state;
this.firstname = firstname;
this.lastname = lastname;
this.c = choice();
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public int compareTo(Contacts contacts) {
if (c == 1){
return this.getLastname().compareTo(contacts.getLastname());
}
else if (c == 2){
return this.getState().compareTo(contacts.getState());
}
else if (c == 3){
return this.getAge().compareTo(contacts.getAge());
}
else return 0;
}
public static int choice() {
System.out.print("Enter number 1,2 or 3: ");
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
return i;
}
#Override
public String toString() {
return "contacts [age=" + age + ", state=" + state + ", firstname=" + firstname + ", lastname=" + lastname
+ "]";
}
}
I don't have enough rep to comment but I feel like it could be your sc.nextInt() statement. try to call sc.close() before you return I and see if that solves your problem.

How to search for an element in an array? and How to add variables with declared methods into an array list?

I have 2 major troubles (that I'm aware of) with this program. Firstly, I don't know how to get FinalGrade and LetterGrade into the array. Secondly, I don't know how to use last name and first name to search for a student in the array. Let me know if you find other problems with my program. Thanks
This is the 1st class
package student;
public class Person {
protected String FirstName, LastName;
//Constructor
public Person(String FirstName, String LastName) {
this.FirstName = FirstName;
this.LastName = LastName;
}
//Getters
public String getFirstName() {
return FirstName;
}
public String getLastName() {
return LastName;
}
//Setters
public void setFirstName(String FirstName) {
this.FirstName = FirstName;
}
public void setLastName(String LastName) {
this.LastName = LastName;
}
}
This is the 2nd class:
package student;
import java.util.ArrayList;
import java.util.Scanner;
public class Student extends Person{
private int HomeworkAve, QuizAve, ProjectAve, TestAve;
private double FinalGrade;
private String LetterGrade;
//Constructor for the averages
public Student(int HomeworkAve, int QuizAve, int ProjectAve, int TestAve, String FirstName, String LastName)
{
super(FirstName, LastName);
this.HomeworkAve = HomeworkAve;
this.QuizAve = QuizAve;
this.ProjectAve = ProjectAve;
this.TestAve = TestAve;
}
//Method to calculate final grade and letter grade
//Final grade calculation
public double CalcGrade (int HomeworkAve, int QuizAve, int ProjectAve, int TestAve)
{
FinalGrade = (double)(0.15*HomeworkAve + 0.05*QuizAve + 0.4 * ProjectAve + 0.4*TestAve);
return FinalGrade;
}
//Letter grade calculation
public String CalcGrade ( double FinalGrade)
{
if ( FinalGrade >= 90.00)
LetterGrade="A";
else if(FinalGrade >= 80.00)
LetterGrade="B";
else if(FinalGrade>=70.00)
LetterGrade="C";
else if(FinalGrade>=60.00)
LetterGrade="D";
else LetterGrade="F";
return LetterGrade;
}
public String getFullName (String FirstName,String LastName)
{
String str1 = FirstName;
String str2 = LastName;
String FullName = str1+","+str2;
return FullName;
}
public Student(int HomeworkAve, int QuizAve, int ProjectAve, int TestAve, double FinalGrade, String LetterGrade, String FirstName, String LastName) {
super(FirstName, LastName);
this.HomeworkAve = HomeworkAve;
this.QuizAve = QuizAve;
this.ProjectAve = ProjectAve;
this.TestAve = TestAve;
this.FinalGrade = FinalGrade;
this.LetterGrade = LetterGrade;
}
//Setters for this student class
public void setHomeworkAve(int HomeworkAve) {
this.HomeworkAve = HomeworkAve;
}
public void setQuizAve(int QuizAve) {
this.QuizAve = QuizAve;
}
public void setProjectAve(int ProjectAve) {
this.ProjectAve = ProjectAve;
}
public void setTestAve(int TestAve) {
this.TestAve = TestAve;
}
public void setFinalGrade(int FinalGrade) {
this.FinalGrade = FinalGrade;
}
public void setLetterGrade(String LetterGrade) {
this.LetterGrade = LetterGrade;
}
//Getters for this student class
public int getHomeworkAve() {
return HomeworkAve;
}
public int getQuizAve() {
return QuizAve;
}
public int getProjectAve() {
return ProjectAve;
}
public int getTestAve() {
return TestAve;
}
public double getFinalGrade() {
return FinalGrade;
}
public String getLetterGrade() {
return LetterGrade;
}
public void DisplayGrade (){
System.out.println(FirstName+" "+LastName+"/nFinal Grade: "+FinalGrade+"/nLetter Grade: "+ LetterGrade);
}
public static void main(String[] args){
Scanner oScan = new Scanner(System.in);
Scanner iScan = new Scanner(System.in);
boolean bContinue = true;
int iChoice;
ArrayList<Student> students = new ArrayList<>();
while (bContinue == true)
{
//The menu
System.out.println("1. New Class List");
System.out.println("2. Search for a Student");
System.out.println("3. Exit");
System.out.println("Choose an item");
iChoice = iScan.nextInt();
//The 1st case: when the user wants to enter the new list
if (iChoice == 1){
System.out.println("Enter the number of students");
int numberOfStudents = iScan.nextInt();
for(int iCount = 0;iCount < numberOfStudents;){
System.out.println("Enter the name for Student " + ++iCount);
System.out.println("Enter First Name");
String FirstName = oScan.nextLine();
System.out.println();
System.out.println("Enter Last Name");
String LastName = oScan.nextLine();
System.out.println();
System.out.println("Enter Homework Average");
int HomeworkAve = iScan.nextInt();
System.out.println();
System.out.println("Enter Quiz Average");
int QuizAve = iScan.nextInt();
System.out.println();
System.out.println("Enter Project Average");
int ProjectAve = iScan.nextInt();
System.out.println();
System.out.println("Enter Test Average");
int TestAve = iScan.nextInt();
System.out.println();
How to get FinalGrade and LetterGrade??
Student hobbit = new Student(HomeworkAve,QuizAve, ProjectAve,TestAve,FirstName, LastName);
students.add(hobbit);
}
}
//The 2nd case: when the user wants to search for a student
else if (iChoice == 2)
{
System.out.println("Enter First Name");
String FirstName = oScan.nextLine();
System.out.println();
System.out.println("Enter Last Name");
String LastName = oScan.nextLine();
System.out.println();
Here is my revised code to find the student but I don't know how to print the array after I found it
int i = 0;
for (Student student : students) {
if (FirstName != null & LastName != null);{
if (student.getFirstName().equals(FirstName) && student.getLastName().equals(LastName)) {
System.out.println(students.get(i)); //this doesn't work
break;
}
i++;
}
}
//The 3r case: when the user wants to exit
else if (iChoice == 3)
{
bContinue = false;
}
}
}
}
You have an ArrayList of type Student and you are doing indexOf on a variable of type String. You will have to traverse the entire ArrayList and then do a comparison to find out if the student name mathces. Sample code:
int i = 0;
for (Student student : students) {
// Add null checks if first/last name can be null
if (student.getFirstName().equals(firstName) && student.getLastName().equals(lastName)) {
System.out.println("Found student at " + i);
break;
}
i++;
}
FinalGrade and LetterGrade are variables in each object, I think you are mistaken about the concept of an Array/ArrayList. The ArrayList only holds each Student object, not the variable in each object. You can go through each student and get their finalGrade and letterGrade with the get* functions. Before doing this, you should make a call to CalcGrade methods so the grades are calculated.

Insert array list in parent class to override with subclasses

I am new to OOP and programming in general. I am having trouble with how to put things in the parent class and call them from the other classes and main.
I have the following arraylist creators in main, but feel to be really OOP these should be in the parent and subclasses and just called from main. Is this is correct can someone help me with how this would work.
How do I get the arraylist in the parent class and then call it correctly from main?
This is what I have for main:
package ooo1;
import java.util.ArrayList;
import java.util.Scanner;
public class ContactList {
public static void main(String[] args) {
Scanner input1 = new Scanner(System.in);
int type = 0;
while(type != 5){
System.out.println("Please select an option:");
System.out.println("Personal Contact: Enter 1");
System.out.println("Business Contact: Enter 2");
System.out.println("Display Personal Contacts: Enter 3");
System.out.println("Display Business Contacts: Enter 4");
System.out.println("5 to quit");
type = input1.nextInt();
if(type == 5){
System.out.println("Goodbye");
break;
}
ArrayList<Contact> contacts = new ArrayList<Contact>();
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();
if(type == 1){
System.out.println("Please enter Birthday: ");
String dateofBirth = input.nextLine();
Contact pcontact = new PersonalContact(contactId, firstName, lastName, address, phoneNumber, emailAddress, dateofBirth);
contacts.add(pcontact);
}
else if(type == 2){
System.out.println("Please enter Job Title: ");
String jobTitle = input.nextLine();
System.out.println("Please enter Organization: ");
String organization = input.nextLine();
Contact bcontact = new BusinessContact(contactId, firstName, lastName, address, phoneNumber, emailAddress, jobTitle, organization);
contacts.add(bcontact);
}
}
}
}
This is what I have for the parent class:
package ooo1;
import java.util.ArrayList;
import java.util.Scanner;
public abstract class Contact {
String contactId;
String firstName;
String lastName;
String address;
String phoneNumber;
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 displayContacts(){
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);
}
}
One of my subclasses: other same just adds a few more variables:
Display Contact(): doesn't work not sure what to do with it either.
/*
* 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 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;
}
#Override
public void displayContacts(){
System.out.print("Personal Contacts: ");
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);
System.out.println("Birthday:" + dateofBirth);
}
}
You probably want something like this.
public class AddressBook<T extends Contact>
{
private List<T> contacts = new ArrayList<T>();
public void addContact(T contact)
{
contacts.add(contact);
}
}
You could instantiate and use this class like this.
AddressBook<Contact> book = new AddressBook<Contact>();
book.add(new PersonalContact(...));
book.add(new BusinessContact(...));
Then over time you have the flexibility to add methods to AddressBook that work with the underlying collection. For instance you might want to search for contacts with a particular name. Or return an iterator of Contacts ordered by a particular attribute.
You can add a method in class Contact :
public void getData(){
// take in all the inputs here, so that you can directly store them in class member variables instead of passing them from main.
}
Assuming that PersonalContact & BusinessContact are inherited classes from Contact.
You can add a method in them:
class PersonalContact extends Contact{
String dateofBirth;
public void getData(){
super.getData(); //calls getData() method from base class
// take DOB as input & store it
}
similarly for BusinessContact class.
I suggest you take a look at abstract classes & interfaces for future use.
The Contact class seems okay. But ContactList not that much. It's supposed to be a data structure for contacts, so there's not reason for main method there.
public class ContactList {
private ArrayList<Contact> contacts;
public ContactList(){
this.contacts = new ArrayList<Contact>();
}
public void addContact(Contact contact){
this.contacts.add(contact);
}
public Contact getContact(int index){
return contacts.get(index);
}
// other methods that work with the data structure
// f.e. searching, deleting, ...
}
and then you could have some ContactUtil class that would take care of reading contact info from user (what you had in you main method).
public final class ContactUtil {
private ContactUtil(){} // we don't want to create instances of this class
public static Contact readNewContact(){
Scanner input1 = new Scanner(System.in);
int type = 0;
...
return contact;
}
}
And finally you will have some class just for main():
public class Main {
public static void main(String[] args){
ContactList myContacs = new ContactList();
myContacts.add(ContactUtil.readNewContact());
Contact contact = ContactUtil.readNewContact();
myContacts.add(contact);
}
}

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