Creating & Writing to a File - java

This program prompts the user to enter the name of the file to be written to for a contact list. They enter info such as name, phone and email and it prints to screen and should write to the file. The inputted info prints to the screen and the file gets created, but noting is written to it. What am I missing?
import java.util.*;
import java.io.*;
public class ContactInfo
{
public static void main(String[] args) throws IOException
{
try
{
int Command = 0;
String FileName = "";
Scanner input = new Scanner(System.in);
Scanner input2 = new Scanner(System.in);
System.out.print("Enter the name of the file for the contact list: ");
FileName = input.nextLine();
System.out.println();
File OutPutFile = new File(FileName);
PrintWriter ContactList = new PrintWriter(OutPutFile);
ContactList.format("%15s%12s%20s\n", "Name", "Phone Number", "Email Address" );
ContactList.format("%15s%12s%20s\n", "------------", "------------", "---------------------" );
String First_Name = "";
String Last_Name = "";
String Remove_Last_Name = "";
String Phone_Number = "";
String Email_Address = "";
//Information InformationObject = new Information(String,String,String,String);
TreeMap<String, Information> Entries = new TreeMap<String, Information>();
do
{
System.out.println();
PrintMenu();
System.out.println();
System.out.print("Enter a command ");
Command = input2.nextInt();
System.out.println();
if (Command == 1)
{
System.out.print("Enter the person's first name: ");
First_Name = input.nextLine();
System.out.println();
System.out.print("Enter the person's last name: ");
Last_Name = input.nextLine();
System.out.println();
System.out.print("Enter the person's phone number: ");
Phone_Number = input.nextLine();
System.out.println();
System.out.print("Enter the person's email address: ");
Email_Address = input.nextLine();
System.out.println();
Information InformationObject = new Information(First_Name, Last_Name, Phone_Number, Email_Address);
Entries.put(InformationObject.getLastName(), InformationObject );
}
if (Command == 2)
{
System.out.print("Enter the last name of the person whom you want to delete from the list: ");
Remove_Last_Name = input.nextLine();
System.out.println();
Entries.remove(Remove_Last_Name);
}
if (Command == 3)
{
for (Map.Entry Document : Entries.entrySet() )
{
Information IO = Entries.get( Document.getKey());
System.out.println( IO.getLastName() + ", " + IO.getFirstName() + " " + IO.getPhoneNumber() + " " + IO.getEmail() );
ContactList.format("%15s%12s%20s\n", IO.getFirstName() + IO.getLastName(), IO.getPhoneNumber(), IO.getEmail() );
}
}
}
while(Command != 4);
}
catch(Exception e)
{
System.out.println("Invalid input");
}
}
public static void PrintMenu()
{
System.out.println();
System.out.println("Add a contact: <1>");
System.out.println("Delete a contact: <2>");
System.out.println("Display contact list: <3>");
System.out.println("Exit: <4>");
System.out.println();
}
}
class Information
{
private String FirstName;
private String LastName;
private String PhoneNumber;
private String Email;
public Information(String FirstName, String LastName, String PhoneNumber, String Email)
{
this.FirstName = FirstName;
this.LastName = LastName;
this.PhoneNumber = PhoneNumber;
this.Email = Email;
}
public void setFirstName(String FirstName)
{
this.FirstName = FirstName;
}
public void setLastName(String LastName)
{
this.LastName = LastName;
}
public void setPhoneNumber(String PhoneNumber)
{
this.PhoneNumber = PhoneNumber;
}
public void setEmail(String Email)
{
this.Email = Email;
}
public String getFirstName()
{
return FirstName;
}
public String getLastName()
{
return LastName;
}
public String getPhoneNumber()
{
return PhoneNumber;
}
public String getEmail()
{
return Email;
}
public String PrintInformation()
{
return LastName + ", " + FirstName + " " + PhoneNumber + " " + Email;
}
}

You forget to close the PrintWriter at the end.
Use finally block to close the object.
ContactList.close();

In this program it reads user entered data and writes it into contact.txt file
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
public class ConsoleToFile {
InputStream is;
public static void main(String[] args) throws IOException {
ArrayList<String> al = new ArrayList<String>();
File file = new File("contact.txt");
System.out.println(file);
FileOutputStream fout = new FileOutputStream(file);
Scanner sc = new Scanner(System.in);
System.out.println("enter ur name");
String name = sc.nextLine();
al.add(name);
System.out.println("enter id");
String id = sc.nextLine();
al.add(id);
System.out.println("enter phone");
String p = sc.nextLine();
al.add(p);
Iterator<String> i = al.iterator();
while (i.hasNext()) {
String s = (String) i.next() + System.lineSeparator();
System.out.println(s);
byte b[] = s.getBytes();
fout.write(b);
}
fout.close();
}
}

Related

How can i access the variable from different class method

This is the main file, im trying to print the result of the Age, Name, Birthdate, etc.
LabExercise1
package labexercise1;
/**
*
* #author user
*/
public class LabExercise1{
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
NewClass newClass = new NewClass();
NewClass.getFirstName();
NewClass.getLastName();
NewClass.getAge();
NewClass.getBirthDate();
NewClass.getGWA();
// TODO code application logic here
System.out.println("My name is " + FirstName + "." + " I am " + Age + " years old and the day that i was born is on " + BirthDate + ". My general weighted average this semester is " + GWA + ".");
}
NewClass
package labexercise1;
import java.util.Scanner;
/**
*
* #author user
*/
public class NewClass {
public static void getFirstName(){
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter First Name: ");
String FirstName = myObj.nextLine(); // Read user input
}
public static void getLastName(){
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter Last Name: ");
String LastName = myObj.nextLine(); // Read user input
}
public static void getAge(){
Scanner myObj = new Scanner(System.in);
System.out.println("Enter your age: ");
int Age = myObj.nextInt();
}
public static void getBirthDate(){
Scanner myObj = new Scanner(System.in);
System.out.println("Enter your BirthDate: ");
String BirthDate = myObj.nextLine();
}
public static void getGWA(){
Scanner myObj = new Scanner(System.in);
System.out.println("Enter your GWA: ");
float GWA = myObj.nextFloat();
}
}
A lot of this is basic Java 101, concepts and ideas which you should be building around "what is an object".
I would, highly, recommend taking the time to go through things like...
Declaring Member Variables
Defining Methods
Providing Constructors for Your Classes
Passing Information to a Method or a Constructor
Understanding Class Members
For example...
import java.text.ParseException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws ParseException {
new Main();
}
public Main() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter First Name: ");
String firstName = scanner.nextLine();
System.out.print("Enter Last Name: ");
String lastName = scanner.nextLine();
System.out.print("Enter Age: ");
int age = scanner.nextInt();
scanner.nextLine();
System.out.print("Enter Birthdate: ");
String dateOfBirth = scanner.nextLine();
System.out.print("Enter GWA: ");
int gwa = scanner.nextInt();
scanner.nextLine();
Person person = new Person(firstName, lastName, age, dateOfBirth, gwa);
System.out.println("First name = " + person.getFirstName());
System.out.println("Last name = " + person.getLastName());
System.out.println("Age = " + person.getAge());
System.out.println("Date of birth = " + person.getDateOfBirth());
System.out.println("GWA = " + person.getGwa());
}
public class Person {
private String firstName;
private String lastName;
private int age;
private String dateOfBirth;
private int gwa;
public Person(String firstName, String lastName, int age, String dateOfBirth, int gwa) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.dateOfBirth = dateOfBirth;
this.gwa = gwa;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public int getGwa() {
return gwa;
}
}
}
Please keep in mind, Stack overflow is NOT a tutorial site/forum and you will, ultimately, be expected to make the effort to learn these basic concepts.

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

How to read values from a text file into hashmap in Java?

I have created class Patient (pojo), where I have declared variables.
I have added getter and setter methods, as well as a constructor:
public class Patient {
private String patientName;
private String phoneNumber;
private int age;
//generate getter and setter method
public String getPatientName() {
return patientName;
}
public void setPatientName(String patientName) {
this.patientName = patientName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//generate constructor
public Patient(String patientName, String phoneNumber, int age) {
this.patientName = patientName;
this.phoneNumber = phoneNumber;
this.age = age;
}
}
I have created an interface PatientDetails and implemented the methods in the Hospital class.
public interface PatientDetails {
public void addpatient();
public void refreshPatient()throws IOException;
}
Here is how the methods are implemented:
public class Hospital implements PatientDetails {`
Scanner scan = new Scanner(System.in);
int token = 0;
String name, mobileNumber;
static HashMap<Integer, Patient> map = new HashMap<Integer, Patient>();
File file = new File("E:\\Patient\\pt.txt");
int age;
public void addpatient() {
BufferedWriter bufferedWriter = null;
FileWriter fileWriter = null;
try {
// true = append file
// write a data in a file
fileWriter = new FileWriter(file, true);
bufferedWriter = new BufferedWriter(fileWriter);
System.out.println("Enter the name");
scan.nextLine();
name = scan.nextLine();
System.out.println("Enter Mobile number must be 10 digit");
mobileNumber = scan.nextLine();
System.out.println("Enter the age");
age = scan.nextInt();
bufferedWriter.write("TokenNumber:" + token + "," + "PatientName:" + name + ",PhoneNumber:" + mobileNumber
+ ",Age :" + age + ";");
// for nextline
bufferedWriter.newLine();
// close file
bufferedWriter.close();
fileWriter.close();
System.out.println("yours Appoint cofirmed....\nPatient Name: " + name + "\nMobile number: " + mobileNumber
+ "\nToken number is: " + token + "\nAge is:" + age);
token++;
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Something went wrong");
e.printStackTrace();
}
}
#Override
public void refreshPatient() throws IOException {
Patient patient=new Patient(mobileNumber, mobileNumber, age);
String filePath = file.getPath();
System.out.println("refreshed successfully");
String line;
BufferedReader reader = new BufferedReader(new FileReader(filePath));
map=new HashMap<>();
while ((line = reader.readLine()) != null) {
String[] parts = line.split(":", 2);
if (parts.length >= 2) {
String key = parts[0];
String value = parts[1];
//map.put(Integer.parseInt(key), value);
} else {
System.out.println("ignoring line: " + line);
}
}
System.out.println(map);
reader.close();
}`)
I have added the patient name, age, and mobile number into the patient.txt file.
When I call the refresh method all the values should come to the map, but I am not getting the Patient class values into the map.
How to fix that?
you should split with , before :.

Using polymorphism to display output of a arraylist

I need to display the first and last names of all contact entered when user selected Display contacts from the menu. I also need to display all details of the contacts when the user inputs the Contact ID entered into the ArrayList.
All I can get to display is the last contact entered. Am I not keeping the ArrayList once I go through once then go back to the menu and enter another contact? Or am I just not calling the print function right still to print all contacts in the arraylist.
If I enter 3 now it just goes back to the first line of the array and wants me to enter a contact ID, and goes through creating a contact again, not displaying what is already there.
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 != 4){
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 Contacts List: Enter 3");
System.out.println("4 to quit");
type = input1.nextInt();
if(type == 4){
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);
for (Contact showcontact: contacts){
System.out.println(showcontact.displayContact());
}
}
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);
for (Contact showcontact: contacts){
System.out.println(showcontact.displayContact());
}
}
else if(type ==3){
for (Contact listcontacts: contacts){
System.out.println(listcontacts.displayFullName());
}
}
}
}
}
Parent Class:
package ooo1;
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 this.contactId; }
public void setFirstName(String input){ this.firstName = input; }
public String getFirstName(){ return this.firstName; }
public void setLastName(String input){ this.lastName = input; }
public String getLastName(){ return this.lastName; }
public void setAddress(String input){ this.address = input; }
public String getAddress(){ return this.address; }
public void setPhoneNumber(String input){ this.phoneNumber = input; }
public String getPhoneNumber(){ return this.phoneNumber; }
public void setEmailAddress(String input){ this.emailAddress = input; }
public String getEmailAddress(){ return this.emailAddress; }
public String displayFullName(){
System.out.println("Contact List:");
return ("First Name:" + this.getFirstName() + "Last Name:" + this.getLastName());
}
public String displayContact(){
return ("ContactID:" + this.getContactId() + "First Name:" + this.getFirstName() + "Last Name:" + this.getLastName() + "Address:" + this.getAddress() + "Phone Number:" + this.getPhoneNumber() + "Email Address" + this.getEmailAddress());
}
}
One of the subclasses: Other same just adds more variables:
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 String displayContact(){
System.out.println("Personal Contacts:");
return super.displayContact() + "Date of Birth: " + this.getDateofBirth();
}
}
So here is a small example on how to use polymorphism, it's basically your classes stripped down to a bar minimum (this is what the SSCCE is about - stripping what's not relevant, like comments and multiple attributes that behaves the same etcetera).
When you call the displayContact() method in the on the Contact objects stored in the ArrayList polymorphism makes sure the correct displayContact method is used.
The reason PersonalContact.displayContacts(); won't work is that you need to call the method on on object as it's not a static method.
I hope this example helps:
// Contact.java
public abstract class Contact {
private final String name;
public Contact(String name) {
this.name = name;
}
public String displayContact() {
return "Contact name: "
+ name + ". Contact type: "
+ this.getClass().getName() + ". ";
}
}
// PersonalContact.java
public class PersonalContact extends Contact {
private final String dateofBirth;
public PersonalContact(String name, String dateOfBirth) {
super(name);
this.dateofBirth = dateOfBirth;
}
#Override
public String displayContact() {
return super.displayContact() + "Date of birth: " + dateofBirth + ".";
}
}
// BusinessContact.java
public class BusinessContact extends Contact {
private final String organization;
public BusinessContact(String name, String org) {
super(name);
this.organization = org;
}
#Override
public String displayContact() {
return super.displayContact() + "Organization: " + organization + ".";
}
}
// ContactList.java
import java.util.ArrayList;
public class ContactList {
public static void main(String[] args) {
ArrayList<Contact> contacts = new ArrayList<>();
PersonalContact personalContact1 = new PersonalContact("John", "1980-01-01");
BusinessContact businessContact1 = new BusinessContact("theCompany", "The Company");
contacts.add(personalContact1);
contacts.add(businessContact1);
for (Contact contact : contacts) {
System.out.println(contact.displayContact());
}
}
}
EDIT added some more referencing issues mentioned in a comment.
The reason you can't print out anything is that the block of code asking for input is always executed as it's not contained in the type 1 or 2 blocks. To remedy that I'd suggest the following changes:
First, move the ArrayList and Scanner to the start of the main method:
ArrayList<Contact> contacts = new ArrayList<Contact>();
Scanner input = new Scanner(System.in);
Then enclose the entire block of code dealing with input in an if block so it looks like this:
if(type==1 || type==2){
Contact contact = null;
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 = new PersonalContact(contactId, firstName, lastName, address, phoneNumber, emailAddress, dateofBirth);
}
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 = new BusinessContact(contactId, firstName, lastName, address, phoneNumber, emailAddress, jobTitle, organization);
}
// add the new contact
contacts.add(contact);
// print out the newly created contact here
System.out.println(contact.displayContact());
}
Also, you don't really need two Scanner-objects, just reuse one of them :)
And you should consider moving the if(type==4) to after the other blocks so that it comes in order (that's just a matter of style though).

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

Categories