Error when trying to add user input to an array - java

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 :)

Related

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

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

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

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

Having trouble with constructors and user-input

I'm working on a little project, but I'm having trouble. It has to do with creating classes, constructors, etc. For the class, all data fields have to be private. I must also have two constructors, one default and one parameterized. Here's the class:
public class PetInfo {
private String petName = "na";
private boolean petType = true;
private String petBreed = "na";
private double petAge = 0;
private double petWeight = 0;
private String ownerName = "na";
public PetInfo(){}
public PetInfo(String name, boolean type, String breed, double age, double weight, String owner){
this.petName = name;
this.petType = type;
this.petBreed = breed;
this.petAge = age;
this.petWeight = weight;
this.ownerName = owner;
}
public String getName (){
return petName;
}
public void setName(String name){
petName = name;
}
public boolean getType(){
return petType;
}
public void setType(boolean type){
petType = type;
}
public String getBreed(){
return petBreed;
}
public void setBreed(String breed){
petBreed = breed;
}
public double getAge(){
return petAge;
}
public void setAge(double age){
petAge = age;
}
public double getWeight(){
return petWeight;
}
public void setWeight(double weight){
petWeight = weight;
}
public String getOwner(){
return ownerName;
}
public void setOwner(String owner){
ownerName = owner;
}
}
Here is what I have in my main function:
import java.util.Scanner;
public class Pp1_C00019540 {
public static void main(String[] args) {
PetInfo[] info = new PetInfo[5];
collectInfo(info);
}
public static void collectInfo(PetInfo[] info){
Scanner input = new Scanner(System.in);
for(int i = 0; i < info.length;i++){
System.out.print("Enter pet name: ");
}
}
}
So it prints "Enter pet name: ", but it won't let me input a name. I tried to do:
info[i] = new PetInfo(input.nextLine());
But it tells me "constructor PetInfo.PetInfo(String, boolean, String, double,double, String) is not applicable. Actual and formal arguments differ in length." Is there something wrong with my class that I'm not catching? I tested it and it seemed to work correctly.
And I'm not looking for a definite answer, I could more than likely figure it out myself. I'm just not sure what's going on, especially when it seemed to me like this would work when I passed the constructor the correct parameters.
Basically, your code is trying to call the PetInfo constructor that takes a single string as input. But based on the code you have, no such constructor exists. You just have the large multi-parameter constructor for PetInfo. You need to call the scanner for input several times before you call the constructor. See the code below:
private static void collectInfo(PetInfo[] info) {
Scanner input = new Scanner(System.in);
try {
for (int i = 0; i < info.length; i++) {
System.out.print("Enter pet name: ");
String petName = input.nextLine();
System.out.print("Enter pet type: ");
boolean petType = input.nextBoolean();
input.nextLine();
System.out.print("Enter pet breed: ");
String petBreed = input.nextLine();
System.out.print("Enter pet age: ");
double petAge = input.nextDouble();
input.nextLine();
System.out.print("Enter pet weight: ");
double petWeight = input.nextDouble();
input.nextLine();
System.out.print("Enter pet owner: ");
String petOwner = input.nextLine();
info[i] = new PetInfo(petName, petType, petBreed, petAge, petWeight, petOwner);
}
}
finally {
input.close();
}
}
Hopefully the code above gives you a good illustration of what I'm talking about. Also, don't forget to call input.nextLine() after calls to nextBoolean() and nextDouble(). Lastly, don't forget to close your input scanner to avoid a resource leak.
Hope that helps.
Well it's simple, when you input using scanner. It takes input in a string, since there is no such constructor which takes string as a parameter it is giving you an error.
You need to take the input from scanner in respective datatypes, store them in variables and then call the constructor. I think what you are trying to do is to call the constructor while taking comma separated input from the scanner, that's not possible.

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

Storing Information in an Address Book

I am required to make an address book application without the use of databases (on memory). I have decided to use ArrayLists to do so. But the problem is that once I input a new name/contact, it overrides any other contacts that I "stored" (or thought I stored) before. I have been trying to figure it out and am outright confused.
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
firstActions();
}
static String firstName;
static String lastName;
static String phoneNumber;
static String search = null;
static public int choice = 0;
static Scanner input = new Scanner (System.in);
static ContactInformation contact;
static ArrayList<String> information = new ArrayList<String>();
public static void firstActions()
{
System.out.println("Address Book Menu: What would you like to do? 1) Input data. 2) Search data. 3) Close.");
choice = input.nextInt();
switch (choice) {
case 1:
inputData();
case 2:
System.out.println("Search by: 1) First Name 2) Last Name 3) Phone Number 4) Zip Code.");
choice = input.nextInt();
switch (choice) {
case 1:
searchName();
break;
case 2:
searchLastName();
case 3:
searchPhoneNumber();
case 4:
//execute search by Zip Code
default:
System.out.println("Please compile again.");
break;
}
break;
case 3:
System.out.println("Application terminated.");
System.exit(0);
default:
System.out.println("Please compile again.");
break;
}
}
public static void inputData ()
{
information = new ArrayList<String>();
contact = new ContactInformation(firstName, lastName, phoneNumber, information);
System.out.println("What is your first name?");
contact.setFirstName(input.next());
information.add(contact.getFirstName());
System.out.println("What is your last name?");
contact.setLastName(input.next());
information.add(contact.getLastName());
System.out.println("What is your phone number?");
contact.setPhoneNumber(input.next());
information.add(contact.getPhoneNumber());
System.out.println("Saved.");
System.out.println("What would you like to do next?");
firstActions();
}
public static void searchName()
{
System.out.println("What is the first name you are looking for?");
search = input.next();
if (search.equals(information.get(0)))
{
System.out.println(information);
System.out.println("What would you like to do next?");
firstActions();
}
else
{
System.out.println("This person is not saved in the address book. Please try again.");
firstActions();
}
}
public static void searchLastName()
{
System.out.println("What is the last name you are looking for?");
search = input.next();
if (search.equals(information.get(1)))
{
System.out.println(information);
firstActions();
}
else
{
System.out.println("This person is not saved in the address book. Please try again.");
firstActions();
}
}
public static void searchPhoneNumber()
{
System.out.println("What is the last name you are looking for?");
search = input.next();
if (search.equals(information.get(2)))
{
System.out.println(information);
firstActions();
}
else
{
System.out.println("This person is not saved in the address book. Please try again.");
firstActions();
}
}
}
Here is my contact information class:
import java.util.ArrayList;
public class ContactInformation {
public String firstName;
public String lastName;
public String phoneNumber;
ArrayList <String> information = new ArrayList<String> ();
public ContactInformation(String firstName, String lastName,
String phoneNumber, ArrayList<String> information) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.phoneNumber = phoneNumber;
this.information = information;
}
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 String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
You first create the ArrayList here:
static ArrayList<String> information = new ArrayList<String>();
but every time you go to the inputData() method, you create a NEW ArrayList:
information = new ArrayList<String>();
From how you wrote the code, I would assume you have a ContactInformation object that you should be placing into the ArrayList.
Change the ArrayList to: static ArrayList<ContactInformation> information = new ArrayList<ContactInformation>();
Then you can create each object and ADD the object to the ArrayList INSTEAD of all the information separately.
EDIT:
Your "ContactInformation" object contains String variables. After you add this object to the ArrayList, you can use a loop to find if the data in the object matches what you are looking for. It should look something like this:
for (int i = 0; i != information.size(); i++) {
if (information.get(i).getFirstName().matches(search)) {
System.out.println("found");
}
}
The if statement says that "if the element 'i's variable 'firstName' in ArrayList 'information' matches the variable 'search', print the word 'found'."
You can obviously change what happens if the name is found, I just simplified it.
everytime you want to insert a name you are creating a new Object from ArrayList
information = new ArrayList<String>();
initizalize this arraylist in your main method and then access it via its variable(information)
The immediate problem is with the first line in your inputData() method:
information = new ArrayList<String>();
You're creating a new ArrayList object every time the method is called, which means the old object, and the data it contained, is lost.

Categories