How to put text file into array and use it with methods - java

So I have a text file named "phone.txt" and I loaded it into an arraylist, the problem is now I don't know how to use that arraylist on my methods in the same class. Let's say on my method "optionP" that I want the customer to be able to search for a name in that arraylist and that person's info will be displayed, how would I do it? So far my code is like this:
import java.util.*;
import java.io.*;
public class Directory {
Scanner kbd = new Scanner(System.in);
ArrayList<Person> persons = new ArrayList<Person>();
public void run() throws FileNotFoundException {
String firstName;
String lastName;
String initial;
String department;
int telNum;
File inFile = new File("phone.txt");
Scanner in = new Scanner(inFile);
while (in.hasNext()) {
Person list;
lastName = in.next();
firstName = in.next();
initial = in.next();
department = in.next();
telNum = in.nextInt();
list = new Person(lastName, firstName, initial, department, telNum);
persons.add(list);
}
in.close();
int i;
i = 0;
while (i < persons.size()) {
System.out.println(persons.get(i).toString());
i++;
}
char userInput = kbd.next().charAt(0);
if (userInput == 'p' || userInput == 'P') {
optionP();
} else if (userInput == 'l' || userInput == 'L') {
optionL();
} else if (userInput == 'r' || userInput == 'R') {
optionR();
} else if (userInput == 'c' || userInput == 'C') {
optionC();
} else if (userInput == 'a' || userInput == 'A') {
optionA();
} else {
optionD();
}
}
public void optionP() {
}
public void optionL() {
}
public void optionR() {
}
public void optionC() {
}
public void optionA() {
}
public void optionD() {
}
public class Person {
String firstName;
String lastName;
String initial;
String department;
int telNum;
public Person(String firstName, String lastName, String initial, String department, int telNum) {
this.firstName = firstName;
this.lastName = lastName;
this.initial = initial;
this.department = department;
this.telNum = telNum;
}
}
}

I'm guessing the file has data and that you are able to see the data when you print it on the console, if not you have to fix that first
Secondly if you wish to read from an arrayList
for(Person p:persons){
//do what you want
}

OptionP needs to go through the ArrayList and finds the corresponding result
Additionally, because you need to iterate the ArrayList, it's better to use LinkedList instead.
You may also need to add a toString method to describe the result.
import java.util.*;
import java.io.*;
public class Directory {
Scanner kbd = new Scanner(System.in);
List<Person> persons = new LinkedList<Person>();
public void run() throws FileNotFoundException {
String firstName;
String lastName;
String initial;
String department;
int telNum;
File inFile = new File("/Users/zhaojing/Desktop/phone.txt");
Scanner in = new Scanner(inFile);
while (in.hasNext()) {
Person list;
lastName = in.next();
firstName = in.next();
initial = in.next();
department = in.next();
telNum = in.nextInt();
list = new Person(lastName, firstName, initial, department, telNum);
persons.add(list);
}
in.close();
int i;
i = 0;
while (i < persons.size()) {
i++;
}
char userInput = kbd.next().charAt(0);
if (userInput == 'p' || userInput == 'P') {
optionP();
} else if (userInput == 'l' || userInput == 'L') {
optionL();
} else if (userInput == 'r' || userInput == 'R') {
optionR();
} else if (userInput == 'c' || userInput == 'C') {
optionC();
} else if (userInput == 'a' || userInput == 'A') {
optionA();
} else {
optionD();
}
}
public Person optionP() {
String userInputFirstName = kbd.next();
for (Person p : persons) {
if (Objects.equals(userInputFirstName, p.firstName)) {
System.out.println(p.toString());
return p;
}
}
return null;
}
public void optionL() {
}
public void optionR() {
}
public void optionC() {
}
public void optionA() {
}
public void optionD() {
}
public class Person {
String firstName;
String lastName;
String initial;
String department;
int telNum;
public Person(String firstName, String lastName, String initial, String department, int telNum) {
this.firstName = firstName;
this.lastName = lastName;
this.initial = initial;
this.department = department;
this.telNum = telNum;
}
#Override
public String toString() {
return "result: Person{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", initial='" + initial + '\'' +
", department='" + department + '\'' +
", telNum=" + telNum +
'}';
}
}
}

Related

Program only reading title of file and nothing else

My program is only reading the name of the file and none of the contents inside. I get an ElementDoesNotExist error every time. The file is in the same folder, and I have no idea why it won't read the contents. I understand that this program is inefficient, and it's my first time using File IO in Java.
import java.util.*;
import java.io.*;
public class Project4
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter the year: ");
int fileYear = input.nextInt();
String userFile = "";
if (fileYear == 2001)
{
userFile = "BabyNames2001.txt";
}
else if (fileYear == 2002)
{
userFile = "BabyNames2002.txt";
}
else if (fileYear == 2003)
{
userFile = "BabyNames2003.txt";
}
else if (fileYear == 2004)
{
userFile = "BabyNames2004.txt";
}
else if (fileYear == 2005)
{
userFile = "BabyNames2005.txt";
}
else if (fileYear == 2006)
{
userFile = "BabyNames2006.txt";
}
else if (fileYear == 2007)
{
userFile = "BabyNames2007.txt";
}
else if (fileYear == 2008)
{
userFile = "BabyNames2008.txt";
}
else if (fileYear == 2009)
{
userFile = "BabyNames2009.txt";
}
else if (fileYear == 2010)
{
userFile = "BabyNames2010.txt";
}
File theFile = new File(userFile);
ArrayList<BabyName> theBabies = loadNames("BabyNames2001.txt", fileYear);
System.out.print("Enter the gender: ");
String babyGender = input.next();
System.out.print("Enter the name: ");
String babyName = input.next();
findName(babyName, fileYear, theBabies);
}
private static ArrayList<BabyName> loadNames(String fileName, int checkYear)
{
ArrayList<BabyName> babies = new ArrayList<BabyName>();
int currentYear = checkYear;
String chooseFile = fileName;
Scanner reader = new Scanner(chooseFile);
while (reader.hasNext())
{
BabyName boy = new BabyName();
BabyName girl = new BabyName();
boy.setYear(currentYear);
girl.setYear(currentYear);
boy.setGender("M");
girl.setGender("F");
String currentRank = reader.next();
boy.setRank(currentRank);
String boyName = reader.next();
int boyTotal = reader.nextInt();
String girlName = reader.next();
int girlTotal = reader.nextInt();
girl.setRank(currentRank);
boy.setName(boyName);
girl.setName(girlName);
boy.setTotal(boyTotal);
girl.setTotal(girlTotal);
babies.add(boy);
babies.add(girl);
}
return babies;
}
private static BabyName findName(String name, int year, ArrayList<BabyName> babies)
{
ArrayList<BabyName> theBabies = babies;
BabyName tempBaby = new BabyName();
String findName = name;
int findYear = year;
for (int baby = 0; baby < 2000; baby++)
{
if (findName == theBabies.get(baby).getName())
{
tempBaby = theBabies.get(baby);
}
}
return tempBaby;
}
}
class BabyName
{
private String rank;
private int year;
private String name;
private String gender;
private int total;
BabyName()
{
}
public String getRank()
{
return rank;
}
public int getYear()
{
return year;
}
public String getName()
{
return name;
}
public String getGender()
{
return gender;
}
public int getTotal()
{
return total;
}
public void setRank(String newRank)
{
this.rank = newRank;
}
public void setYear(int newYear)
{
this.year = newYear;
}
public void setName(String newName)
{
this.name = newName;
}
public void setGender(String newGender)
{
this.gender = newGender;
}
public void setTotal(int newTotal)
{
this.total = newTotal;
}
}
Your problem is here:
Scanner reader = new Scanner(chooseFile);
The Scanner class has multiple overloaded constructors. chooseFile is a String, so you are calling Scanner(String) when what you probably want is Scanner(File). Because of this your code does not read any files, it is reading the literal string "BabyNames2001.txt".
The solution is to simply pass a File instead of a String, or something along the lines of:
Scanner reader = new Scanner(new File(chooseFile));

Difficulty setting and updating objects in a Sorted ArrayList [duplicate]

This question already has answers here:
method in class cannot be applied to given types
(7 answers)
Closed 2 years ago.
I wish to be able to update information about objects entered by a user. I would like the user to enter a book name and user name to take out the book, as well as being able to return it with the same information. The objects have to be inserted into the right place in my sortedarraylists. Each user is assumed to be unique and each book can only be taken out by one user (who can take out up to 3 books).
When I try to compile my code, I get this error message:
java: method issueBook in class Driver cannot be applied to given types;
required: Book,User
found: no arguments
reason: actual and formal argument lists differ in length
This corresponds to issueBook(); in case i of my menu.
I also have User and Book classes that implement Comparable<Book> etc. I tried to omit as much irrelevant code as I could, such as the filereader to scan in new user and book objects. I included the book and user classes in case they need to be looked at (I think they are mostly fine). Please let me know if you need any more details however.
import java.io.*;
import java.util.Scanner;
public class Driver {
static Scanner sc = new Scanner(System.in);
private static void mainMenu() {
System.out.println("------------------------------\n"+
"f: Finish running the program\n" +
"b -Display on the screen the information about all the books in the library\n" +
"u -Display on the screen the information about all the users.\n" +
"i -Update the stored data when a book is issued to a user\n" +
"r -Update the stored data when a user returns a book to the library\n" +
"------------------------------\n" +
"Type a letter and press Enter\n");
}
private static User readNames() throws User.InvalidBookLimitException {
System.out.println("Enter the user's firstname: ");
String firstName = sc.next();
System.out.println("Enter the user's surname: ");
String surName = sc.next();
sc.nextLine(); //TODO check this
return new User(firstName, surName, 0);
}
private static User readUserData(User user) throws User.InvalidBookLimitException {
User u = readNames();
System.out.println("Enter " + user + "'s age, and press Enter");
int numberOfBooks = sc.nextInt();
sc.nextLine();
return new User(u.getFirstName(), u.getSurName(),u.getNumberOfBooks());
}
private static Book readBookName (){
System.out.println("Type in the name of the book");
String bookName = sc.nextLine();
return new Book(bookName);
}
/* public SortedArrayList<User> sortedUsers = new SortedArrayList<>(); public SortedArrayList<Book> sortedBooks = new SortedArrayList<>();*/
//If this part is commented out, I get errors since I can't seem to access the arraylists in the
// main method for the issueBook/returnBook methods.
public void issueBook(Book book, User user){
for (Book b : sortedBooks){
if(b.equals(book)){
b.loanStatus(true);
/*b.setLoanerNames(user);*/ b.setLoanerNames("John", "Doe");
break;
}
}
for (User u: sortedUsers){
if(u.equals(user)){
u.setNumberOfBooks(u.getNumberOfBooks()+1);
}
}
}
public void returnBook(Book book, User user){
for (Book b : sortedBooks){
if(b.equals(book)){
b.loanStatus(false);
b.setLoanerNames(null, null);
break;
} for (User u: sortedUsers){
if(u.equals(user)){
u.setNumberOfBooks(u.getNumberOfBooks()-1);
}
}
}
}
public static <E> void main(String[] args) throws FileNotFoundException, User.InvalidBookLimitException {
//These SortedArrayLists have been derived from the sorted arraylist class
SortedArrayList<User> sortedUsers = new SortedArrayList<>();
SortedArrayList<Book> sortedBooks = new SortedArrayList<>();
mainMenu(); //main menu printing method
char ch = sc.next().charAt(0);
sc.nextLine();
while (ch !='f') //the program ends as desired if f is pressed
{ switch(ch){
case 'b':
System.out.println("Displaying information about all books in the library: ");
/*for (Object item : sortedBooks) {
System.out.println(sortedBooks.toString());
}*/
System.out.println(sortedBooks/*.toString()*/);
break;
case 'u':
System.out.println("Displaying information about all users");
System.out.println(sortedUsers/*.toString()*/);
break;
case 'i':
System.out.println("Enter the loaning out data. ");
System.out.println("Enter the user's first name and surname: ");
readNames();
System.out.println("Enter the name of the book: ");
readBookName();
issueBook();
or maybe if(u1.compareTo(u2) == 0)*/
break;
case 'r':
System.out.println("Please the details of the book to be returned: ");
/*Book b = new Book("test1", "test2", true, "lol","lol2");*/
//this was just a test and didn't work
/*returnBook(b);*/
break;
default:
System.out.println("Invalid input, please enter f, b, i or r");
}
mainMenu();
ch = sc.next().charAt(0);
sc.nextLine();
}
}
}
My sorted arraylist class with a (working) insert method:
import java.util.ArrayList;
public class SortedArrayList<E extends Comparable<E>> extends ArrayList<E> {
//no need for a generic in the insert method as this has been declared in the class
public void insert(E value) {
if (this.size() == 0) {
this.add(value);
return; }
for (int i = 0; i < this.size(); i++) {
int comparison = value.compareTo((E) this.get(i));
if (comparison < 0) {
this.add(i, value);
return; }
if (comparison == 0) {
return; }
}
this.add(value);
}
User class:
import java.io.PrintWriter;
public class User implements Comparable<User> {
private String firstName;
private String surName;
private int numberOfBooks;
public User(){
firstName = "";
surName = "";
numberOfBooks = 0;
}
public class InvalidBookLimitException extends Exception{
public InvalidBookLimitException(){
super("Invalid number of books");
}
}
public User(String name1, String name2, int books) throws InvalidBookLimitException {
this.firstName = name1;
this.surName = name2;
if (books>3) throw new InvalidBookLimitException ();
this.numberOfBooks = books;
}
public String getFirstName() {
return firstName;
}
public String getSurName(){
return surName;
}
public int getNumberOfBooks(){
return numberOfBooks;
}
public boolean borrowMoreBooks(){
return numberOfBooks < 3;
}
public void setNumberOfBooks(int numberOfBooks){
this.numberOfBooks=numberOfBooks;
}
public void setUser(String name1, String name2, int books){
firstName = name1;
surName = name2;
numberOfBooks = books;
}
public boolean userNameTest (User otherUser){
return (firstName.equals(otherUser.firstName) && surName.equals(otherUser.surName));
}
/* public boolean loanAnotherBook(){
return !(numberOfBooks<3);
numberOfBooks++;
}*/
public void printName(PrintWriter f){f.println(firstName+ " " + surName);}
/*
public void setUser(User user) {
if (loanStatus == false){
loanStatus = Driver.readNameInput();
loanStatus = true;
}
}*/
#Override
public String toString(){
return "Name: " + firstName + " " + surName + " | Number of books: " + numberOfBooks;
}
public int compareTo(User u) {
/* int snCmp = surName.compareTo(u.surName);
if (snCmp != 0)
return snCmp;
else{
int fnCmp = firstName.compareTo(u.firstName);
if (fnCmp !=0)
return fnCmp;
}*/
int fnCmp = firstName.compareTo(u.firstName);
if (fnCmp != 0) return fnCmp;
int snCmp= surName.compareTo(u.surName);
if (snCmp !=0) return snCmp;
else return numberOfBooks -u.numberOfBooks;
}
#Override
public boolean equals(Object obj) {
return super.equals(obj);
}
}
Book class:
public class Book implements Comparable<Book>{
public String bookName;
public String authorName;
public boolean loanStatus;
public String loanerFirstName;
public String loanerSurName;
//if boolean loanStatus == true private string loaner name
public Book(){
bookName = "";
authorName = "";
loanStatus = false;
loanerFirstName = null;
loanerSurName = null;
}
Book(String book, String author, boolean loanStatus, String loanerFirstName, String loanerSurName) {
this.bookName = book;
this.authorName = author;
this.loanStatus = loanStatus;
this.loanerFirstName = loanerFirstName;
this.loanerSurName = loanerSurName;
}
Book(String book){
this.bookName=book;
}
public String getBookName(){
return bookName;
}
public String getAuthorName(){
return bookName;
}
public boolean getLoanStatus(){
return loanStatus;
}
public String getLoanerFirstName(){
return loanerFirstName;
}
public String getLoanerSurName(){
return loanerSurName;
}
public void setBook(String book, String author, boolean loanStatus, String loanerFirstName, String loanerSurName){
bookName = book;
authorName = author;
loanStatus = loanStatus;
loanerFirstName = loanerFirstName;
loanerSurName = loanerSurName;
}
public void setBookName(String bookName){
this.bookName=bookName;
}
public void loanStatus(boolean loanStatus){
this.loanStatus=loanStatus;
}
public void setLoanerNames(String loanerFirstName, String loanerSurName){
this.loanerFirstName=loanerFirstName;
this.loanerSurName=loanerSurName;
}
/* public boolean nameTest (User otherUser){
return (loanerFirstName.equals(otherUser.loanerFirstName)&& loanerSurName.equals(otherUser.loanerSurName));
}
*/
public String toString(){
return "Book: " + bookName + " | Author: " + authorName + " | Loan status: " + loanStatus + " | Loaned to: " + loanerFirstName + " " + loanerSurName ;
}
//this may be redundant TODO
/* public void setLoanStatus(User user){
loanStatus = false;
}*/
//This compare method allows new user objects to be compared to ones in the
#Override //sortedArrayList, enabling the insertion method.
public int compareTo(Book b) {
int bnCmp = bookName.compareTo(b.bookName);
if (bnCmp != 0) return bnCmp;
int anCmp= authorName.compareTo(b.authorName);
if (anCmp !=0) return anCmp;
// int lsCmp= loanStatus.(b.loanStatus);
// if (lsCmp !=0) return lsCmp;
int lrfnCmp =loanerFirstName.compareTo(b.loanerFirstName);
if (lrfnCmp !=0) return lrfnCmp;
int lrlnCmp =loanerSurName.compareTo(b.loanerSurName);
if (lrlnCmp !=0) return lrlnCmp;
else return 0;
}
}
User user = readNames();
Book book = readBookName();
issueBook(book, user);
You have to pass the user and book which you have created while calling the issueBook method.

How do I fix a mismatch exception in Java?

I keep getting an error called "java.util.Mismatchexpection: null". I'm not sure how to fix this. It points to the grade = fileInput.nextInt(); line.
Here are the classes I'm using:
import java.util.Scanner;
import java.io.*;
public class Students
{
public static void printAllStudents(Student[] students){
for(int i=0;i<students.length;i++)
{
System.out.println(students[i]);
}
}
public static void printAllStudentsByFirstName(Student[] students,String firstName){
String name=firstName.split(" ")[1];
int len=name.length();
for (int i=0;i<students.length;i++){
try{
if(students[i].getFname().substring(0, len).equalsIgnoreCase(name)){
System.out.println(students[i]);
}
}
catch (Exception e) {
// TODO: handle exception
}
}
}
public static void printAllStudentsByLastName(Student[] students,String lastName){
String name=lastName.split(" ")[1];
int len = name.length();
for(int i=0;i<students.length;i++){
try{
if(students[i].getLname().substring(0, len).equalsIgnoreCase(name)){
System.out.println(students[i]);
}
}
catch (Exception e) {
// TODO: handle exception
}
}
}
public static void printAllStudentsByGrades(Student[] students,String interval){
int start=Integer.parseInt(interval.split(" ")[1]);
int end=Integer.parseInt(interval.split(" ")[2]);
for(int i=0;i<students.length;i++){
if(students[i].getGrade()>=start && students[i].getGrade()<=end){
System.out.println(students[i]);
}
}
}
public static void sort(Student[] students)
{
int n = students.length;
int k;
for (int m = n; m >= 0; m--) {
for (int i = 0; i < n - 1; i++) {
k = i + 1;
if (students[i].getGrade() > students[k].getGrade())
{
Student temp=new Student();
temp = students[k];
students[k]=students[i];
students[i]=temp;
}
}
}
printAllStudents(students);
}
public static void main (String[] args) throws IOException
{
String first_name, last_name, line = "";
int grade, lines = 0, i;
char ch;
Scanner sc = new Scanner(System.in);
Scanner fileInput = new Scanner(new File("students.txt"));
//Counting the number of lines in the file.
while (fileInput.hasNext())
{
line = fileInput.next();
lines++;}
fileInput = new Scanner(new File("students.txt"));
//Declaring Student array of size lines.
Student[] students=new Student[lines];
i = 0;
while (fileInput.hasNext())
{
first_name = fileInput.nextLine();
last_name = fileInput.nextLine();
grade = fileInput.nextInt();
Student st = new Student(first_name, last_name, grade);
students[i++] = st;
}
System.out.println("Please choose from below operations: ");
System.out.println("1. printall");
System.out.println("2. firstname <name>");
System.out.println("3. lastname <name>");
System.out.println("4. interval m n");
System.out.println("5. sort");
System.out.println("6. end");
while (true)
{
System.out.println("Enter choice:");
String choice = sc.nextLine();
if(choice.equals("printall"))
printAllStudents(students);
else if(choice.indexOf("firstname")==0)
printAllStudentsByFirstName(students, choice);
else if(choice.indexOf("lastname") == 0)
printAllStudentsByLastName(students, choice);
else if(choice.indexOf("interval") == 0)
printAllStudentsByGrades(students, choice);
else if(choice.equals("sort"))
sort(students);
else if(choice.equals("end"))
break;
}
}
}
public class Student
{
private String fname, lname;
private int grade;
public Student()
{
super(); //gives us the ability to override
}
public Student (String fname, String lname, int grade)
{
this.fname = fname;
this.lname = lname;
this.grade = grade;
}
public String getFname() {
return fname;
}
public void setFname (String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
public String toString()
{
return fname + " " + lname + "\t" + grade;
}
}
Any help will be much appreciated.
A MismatchException is triggered when the Scanner runs into unexpected input. In your case, the Scanner is picking up null when it is expecting int input for fileInput.nextInt().
This has to do with the formatting of student.txt and how you're parsing it; try running the code in debug, step-by-step, in your IDE (if you're using one) to pinpoint how to fix your text-file parsing.

How do you retrieve all of the records that a user inputs into an arraylist in java

I am trying to retrieve every record that an arraylist contains. I have a class called ContactList which is the super class of another class called BusinessContacts. My first task is to print only the first name and last name of a contact. The second task is to print details of a contact that's related to its id number. The ContactList class has all the instance variables and the set/get methods and the toString() method. The BusinessContact class consists of only two instance variables that need to be appended to the ContactList class. How is can this be worked out? The code is below:
The ContactList class:
package newcontactapp;
public abstract class ContactList {
private int iD;
private String firstName;
private String lastName;
private String adDress;
private String phoneNumber;
private String emailAddress;
// six-argument constructor
public ContactList(int id, String first, String last, String address, String phone, String email) {
iD = id;
firstName = first;
lastName = last;
adDress = address;
phoneNumber = phone;
emailAddress = email;
}
public ContactList(){
}
public void displayMessage()
{
System.out.println("Welcome to the Contact Application!");
System.out.println();
}
public void displayMessageType(String type)
{
System.out.println("This is a " + type);
System.out.println();
}
public int getiD() {
return iD;
}
public void setiD(int id) {
iD = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String first) {
firstName = first;
}
public String getLastName() {
return lastName;
}
public void setLastName(String last) {
lastName = last;
}
public String getAdDress() {
return adDress;
}
public void setAdDress(String address) {
adDress = address;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phone) {
phoneNumber = phone;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String email) {
emailAddress = email;
}
public String toString(){
return getiD() + " " + getFirstName() + " " + getLastName() + " " + getAdDress() + " " + getPhoneNumber() + " " + getEmailAddress() + "\n" ;
}
}
The BusinessContacts class:
package newcontactapp;
public class BusinessContacts extends ContactList {
private String jobTitle;
private String orGanization;
//
public BusinessContacts(int id, String first, String last, String address, String phone, String email, String job, String organization){
super();
jobTitle = job;
orGanization = organization;
}
public BusinessContacts(){
}
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String job) {
jobTitle = job;
}
public String getOrGanization() {
return orGanization;
}
public void setOrGanization(String organization) {
orGanization = organization;
}
//#Override
public String toString(){
return super.toString()+ " " + getJobTitle()+ " " + getOrGanization() + "\n";
}
}
Here is my main method class:
package newcontactapp;
import java.util.ArrayList;
//import java.util.Iterator;
import java.util.Scanner;
public class NewContactAppTest {
//ArrayList<ContactList> fullList = new ArrayList<>();
ArrayList<ContactList> bContacts = new ArrayList<>();
ArrayList<ContactList> pContacts = new ArrayList<>();
public static void main(String [] args)
{
ContactList myContactList = new ContactList() {};
myContactList.displayMessage();
new NewContactAppTest().go();
}
public void go()
{
ContactList myContactList = new ContactList() {};
System.out.println("Menu for inputting a Business Contact or Personal Contact");
System.out.println();
Scanner input = new Scanner(System.in);
System.out.println("Please enter a numeric choice below: ");
System.out.println();
System.out.println("1. Add a Business Contact");
System.out.println("2. Add a Personal Contact");
System.out.println("3. Display Contacts");
System.out.println("4. Quit");
System.out.println();
String choice = input.nextLine();
if(choice.contains("1")){
String type1 = "Business Contact";
myContactList.displayMessageType(type1);
businessInputs();
}
else if(choice.contains("2")){
String type2 = "Personal Contact";
myContactList.displayMessageType(type2);
personalInputs();
}
else if(choice.contains("3")) {
displayContacts();
displayRecord();
}
else if(choice.contains("4")){
endOfProgram();
}
}
public void businessInputs()
{
BusinessContacts myBcontacts = new BusinessContacts();
//ContactList myContactList = new ContactList() {};
//ContactList nameContacts = new ContactList() {};
bContacts.clear();
int id = 0;
myBcontacts.setiD(id);
Scanner in = new Scanner(System.in);
while(true){
id = id + 1;
myBcontacts.setiD(id);
//myContactList.setiD(id);
System.out.println("Enter first name ");
String firstName = in.nextLine();
//nameContacts.setFirstName(firstName);
//myContactList.setFirstName(firstName);
myBcontacts.setFirstName(firstName);
System.out.println("Enter last name: ");
String lastName = in.nextLine();
//nameContacts.setLastName(lastName);
//myContactList.setLastName(lastName);
myBcontacts.setLastName(lastName);
System.out.println("Enter address: ");
String address = in.nextLine();
//myContactList.setAdDress(address);
myBcontacts.setAdDress(address);
System.out.println("Enter phone number: ");
String phoneNumber = in.nextLine();
//myContactList.setPhoneNumber(phoneNumber);
myBcontacts.setPhoneNumber(phoneNumber);
System.out.println("Enter email address: ");
String emailAddress = in.nextLine();
//myContactList.setEmailAddress(emailAddress);
myBcontacts.setEmailAddress(emailAddress);
System.out.println("Enter job title: ");
String jobTitle = in.nextLine();
myBcontacts.setJobTitle(jobTitle);
System.out.println("Enter organization: ");
String organization = in.nextLine();
myBcontacts.setOrGanization(organization);
//bContacts.add(myContactList);
bContacts.add(myBcontacts);
//names.add(nameContacts);
//System.out.println("as entered:\n" + bContacts);
System.out.println();
System.out.println("Enter another contact?");
Scanner input = new Scanner(System.in);
String choice = input.nextLine();
if(choice.equalsIgnoreCase("Y")) {
continue;
}
else{
break;
}
}
//bContacts.add(myBcontacts);
go();
}
public void personalInputs(){
ContactList myContactList = new ContactList() {};
PersonalContacts myPcontacts = new PersonalContacts();
Scanner in = new Scanner(System.in);
int id;
id = 1;
while(true){
System.out.println("Enter first name; ");
String firstName = in.nextLine();
myContactList.setFirstName(firstName);
myPcontacts.setFirstName(firstName);
System.out.println("Enter last name: ");
String lastName = in.nextLine();
myContactList.setLastName(lastName);
myPcontacts.setLastName(lastName);
System.out.println("Enter address: ");
String address = in.nextLine();
myContactList.setAdDress(address);
myPcontacts.setAdDress(address);
System.out.println("Enter phone number: ");
String phoneNumber = in.nextLine();
myContactList.setPhoneNumber(phoneNumber);
myPcontacts.setPhoneNumber(phoneNumber);
System.out.println("Enter email address: ");
String emailAddress = in.nextLine();
myContactList.setEmailAddress(emailAddress);
myPcontacts.setEmailAddress(emailAddress);
System.out.println("Enter birth date");
String dateOfBirth = in.nextLine();
myPcontacts.setDateOfBirth(dateOfBirth);
//pContacts.add(myContactList);
pContacts.add(myPcontacts);
id = id + 1;
myContactList.setiD(id);
System.out.println();
System.out.println("Enter another contact?");
Scanner input = new Scanner(System.in);
String choice = input.nextLine();
if (choice.equalsIgnoreCase("y")) {
continue;
}
else{
break;
}
}
go();
}
public void displayContacts(){
System.out.println();
for(ContactList name : bContacts){
System.out.println(name.getiD() + " " + name.getFirstName()+ " " + name.getLastName());
}
}
public void displayRecord(){
System.out.println();
System.out.println("Do you wish to see details of contact?");
Scanner input = new Scanner(System.in);
String choice = input.nextLine();
if(choice.equalsIgnoreCase("Y")) {
System.out.println();
System.out.println("Enter the numeric key from the list to see more specific details of that record");
System.out.println();
Scanner key = new Scanner(System.in);
System.out.println();
ContactList record = new ContactList() {};
for(int i = 0; i < bContacts.size(); i++){
record = bContacts.get(i);
System.out.println(record.toString());
}
}
else{
go();
}
/* else{
System.out.println();
System.out.println("This is a Personal Contact");
System.out.println();
for(int j = 0; j < pContacts.size(); j++){
ContactList pList = pContacts.get(j);
pList = pContacts.get(j);
System.out.println(pList.toString());
}
}*/
}
public void endOfProgram(){
System.out.println("Thank you! Have a great day!");
Runtime.getRuntime().exit(0);
}
}
If you're looking to get a value based on ID, try making a method that iterates over the contents of the ArrayList to find one that matches:
public ContactList getContactList(int id) {
for (ContactList list : /*your ContactList List object*/) {
if (list.getiD() == id) {
return list;
}
}
return null;
}
This will return null if none is found, or the first result in the list.

adding objects to an ArrayList using an abstract class

I'm trying to add animal objects to a pet ArrayList using an accept method but I am getting an error saying cannot find symbol. I've been over it a bunch of times and am just not seeing it.
Thanks for your help.
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Scanner;
public class Shelter2 implements AnimalShelter {
private ArrayList<Animal2> pet;
private int Id;
Scanner in = new Scanner(System.in);
public Shelter2() {
pet = new ArrayList<Animal2>();
SimpleDateFormat DateFormat = new SimpleDateFormat("MM-dd-yyyy");
Date now = new Date();
String today = DateFormat.format(now).toString();
// pet.add(new Cat("Snow White", "Domestic Short Hair", "White", "F",
// "01-01-2012", null));
// pet.add(new Dog("Buster", "Beagle", "Brown/White/Black", "male",
// "12-25-2011", null));
// pet.add(new Reptile("Jack", "Lizard", "01-31-2012", null));
}
public String allAnimals() {
String str = "";
for (Animal2 p : pet) {
str = str + p + "\n\n";
}
return str;
}
public String available() {
String str = "";
for (int i = 0; i < pet.size(); i++) {
Animal2 p = pet.get(i);
if (p.getAdoptedDate() == null) {
str = str + p + "\n\n";
}
}
return str;
}
public String adopted() {
String str = "";
for (int i = 0; i < pet.size(); i++) {
Animal2 p = pet.get(i);
if (p.getAdoptedDate() != null) {
str = str + p + "\n\n";
}
}
return str;
}
public boolean adopt(int id) {
return true;
}
public boolean accept(Animal2 pet) {
String type = null;
System.out.println("What type of animal? (Cat, Dog, Reptile)");
type = in.next();
if (type == "Cat") {
System.out.println("Enter name: ");
String name = in.next();
System.out.println("Enter description: ");
String desc = in.next();
System.out.println("Enter color: ");
String color = in.next();
System.out.println("Enter sex: ");
String sex = in.next();
pet.add(new Cat(name, desc, color, sex, null, null));
}
return true;
}
}
public abstract class Animal2 {
public String name;
public String arrivalDate;
public String adoptedDate;
public String getName() {
return new String(name);
}
public void setName(String name) {
this.name = name;
}
public String getArrivalDate() {
return new String(arrivalDate);
}
public void setArrivalDate(String arrivalDate) {
this.arrivalDate = arrivalDate;
}
public String getAdoptedDate() {
return adoptedDate;
}
public void setAdoptedDate(String adoptedDate) {
this.adoptedDate = adoptedDate;
}
#Override
public String toString() {
return "\nName: " + name + "\nArrival Date: " + arrivalDate
+ "\nAdopted Date: " + adoptedDate;
}
}
class Cat extends Animal2 {
String desc;
String color;
String sex;
char s;
Cat(String name, String desc, String color, String sex, String arrivalDate,
String adoptedDate) {
super.setName(name);
super.setArrivalDate(arrivalDate);
super.setAdoptedDate(adoptedDate);
setDesc(desc);
setColor(color);
setSex(sex);
char s = ' ';
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
s = sex.toLowerCase().charAt(0);
if ((s == 'f') || (s == 'm')) {
this.sex = sex;
} else {
System.err.println("Illegal value for Cat sex field - " + sex);
}
}
#Override
public String toString() {
if (s == 'f') {
sex = "Female";
} else if (s == 'm') {
sex = "Male";
} else {
sex = null;
}
return "\nCat: " + super.toString() + "\nDescription: " + desc
+ "\nColor: " + color + "\nSex: " + sex;
}
}
class Dog extends Animal2 {
String bred;
String color;
String sex;
char s;
Dog(String name, String bred, String color, String sex, String arrivalDate,
String adoptedDate) {
super.setName(name);
super.setArrivalDate(arrivalDate);
super.setAdoptedDate(adoptedDate);
setBred(bred);
setColor(color);
setSex(sex);
char s = ' ';
}
public String getBred() {
return bred;
}
public void setBred(String bred) {
this.bred = bred;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
s = sex.toLowerCase().charAt(0);
if ((s == 'f') || (s == 'm')) {
this.sex = sex;
} else {
System.err.println("Illegal value for Dog sex field - " + sex);
}
}
#Override
public String toString() {
if (s == 'f') {
sex = "Female";
} else if (s == 'm') {
sex = "Male";
} else {
sex = null;
}
return "Dog: " + super.toString() + "\nBred: " + bred + "\nColor: "
+ color + "\nSex: " + sex;
}
}
class Reptile extends Animal2 {
String type;
Reptile(String name, String type, String arrivalDate, String adoptedDate) {
super.setName(name);
super.setArrivalDate(arrivalDate);
super.setAdoptedDate(adoptedDate);
setType(type);
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
#Override
public String toString() {
return "Reptile: " + super.toString() + "\nType: " + type;
}
}
I'm going to go out on a limb here and say that this line is giving you the error:
pet.add(new Cat(name, desc, color, sex, null, null));
You're getting this error because pet, within the scope of your accept method, is an Animal2. If you want to reference the field named pet, try:
this.pet.add(new Cat(name, desc, color, sex, null, null));
Also, in your Dog and Cat classes, you are not setting s. You are creating a new variable s and setting it to ' ' (char s = ' ';). I'm not sure how that will affect your project, but you probably aren't intending to do it.

Categories

Resources