Separating strings and matching them with text file in java - java

I have a text file which contains a student number (9 digits), pin (4 digits), first name, last name. Which looks like this:
456864324,4965,Eves,Dalton
457642455,2164,Jagger,Michael
132435465, 3578,McIvar, Alan
543247531,2854,Jones, Alan
The student enters its student number and then pin. The program matches his input to the text file and checks if it matches or not.
So far I've separated the text line by line and stored it into an ArrayList and then thought about splitting it with ",". I've also thought about using Maps but cannot figure out how I will store the names with it as well.
String studentdb = sn_field.getText(); //get student number from input
String pindb = pin_field.getText(); //get pin from input
try {
File f = new File("file name");
Scanner sc = new Scanner(f);
ArrayList<String> number= new ArrayList<String>();
ArrayList<String> pswd = new ArrayList<String>();
while(sc.hasNextLine()){
String line = sc.nextLine();
// = line.split("\n");
String sn = line;
people.add(sn);
}
//if(people.contains(studentdb)){
//System.out.println("pass");}
} catch (FileNotFoundException f) {
System.out.print("file not found");
}
All in all if the student number and pin both are wrong, it should give an error, if both are correct and match, it passes. Any help would be appreciated as I'm just a beginner at Java.

I was able to process your file with the following example. Thanks for the problem as it provided a fun playground for some of the new features in Java 8 that I'm still getting familiar with . . .
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;
import java.util.Scanner;
public class StudentInformationMatcher
{
private static final Path FILE_PATH = Paths.get("C:\\projects\\playground\\src\\main\\resources\\studentinfo.txt");
public static void main(String[] args) throws IOException
{
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter your student number: ");
String studentNumber = scanner.next();
System.out.print("Please enter your pin: ");
String pin = scanner.next();
Optional<Person> matchingPersonRecord =
Files.lines(FILE_PATH)
.map(line -> line.split(","))
.map(csvValues -> new Person(csvValues))
.filter(person -> person.getStudentNumber().equals(studentNumber) && person.getPin().equals(pin))
.findFirst();
if (matchingPersonRecord.isPresent())
{
Person matchingPerson = matchingPersonRecord.get();
System.out.println("Hello " + matchingPerson.getFirstName() + " " + matchingPerson.getLastName());
}
else
{
System.out.println("No matching record found");
}
}
private static class Person
{
private final String studentNumber;
private final String pin;
private final String lastName;
private final String firstName;
private Person(String[] csvValues)
{
this.studentNumber = csvValues[0].trim();
this.pin = csvValues[1].trim();
this.lastName = csvValues[2].trim();
this.firstName = csvValues[3].trim();
}
private String getStudentNumber()
{
return studentNumber;
}
private String getPin()
{
return pin;
}
private String getLastName()
{
return lastName;
}
private String getFirstName()
{
return firstName;
}
}
}

Here an idea how you could achieve this:
Create a "student" class:
class student {
private String lastname;
private String firstname;
private String studentId;
private String pin;
// Getter and Setter methods
public static createNewStudent(String line) {
// split here the line and save the fields in the member variables
}
public boolean checkPinCode(String pin) {
return this.pin.equals(pin);
}
}
In your loop you can create student objects and add them to a Hashtable.
The key is the studentId and the value is the student object.
You can retrieve a student object from the hashtable with the entered key and check if the pin passes.

Related

Use an arraylist multiple times inside different parts of JAVA code

I am using an array list to store values from user input by constructing an interactive menu for them to choose. My two choices so far, provides the user to input data to the list and to read the whole content of a list. The code I created so far consists of two classes.
My main class,
package com.andrekreou;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Welcome to the personnel address book");
System.out.println("In the following menu, a whole selection of services is provided");
Scanner user_input = new Scanner(System.in);
while (true){
showMenu();
String selection = user_input.next();
if (selection.equals("1")){
System.out.println("Below you can see all of the data being provided");
for (String personnel : catalog) { } //ERROR: Cannot resolve symbol catalog
}else if (selection.equals("2")){
ArrayList<String> catalog = new ArrayList<>();
Personnel p1 = new Personnel();
System.out.println("Please insert the data for the new contact");
System.out.println("Input the fullname:");
Scanner scan = new Scanner(System.in);
String full_name = scan.nextLine();
p1.setFull_name(full_name);
catalog.add(full_name);
System.out.println("You inserted the following fullname: "+p1.getFull_name());
System.out.println("Input the phonenumber:");
Scanner phone_number_input = new Scanner(System.in);
String phone_number = phone_number_input.next();
p1.setPhone_number(phone_number);
catalog.add(phone_number);
System.out.println("You inserted the following phonenumber: "+p1.getPhone_number());
System.out.println("Input the address:");
Scanner address_input = new Scanner(System.in);
String address = address_input.nextLine();
p1.setAddress(address);
catalog.add(address);
System.out.println("You inserted the following address: "+p1.getAddress());
System.out.println("Εισάγετε την διεύθυνση e-mail:");
Scanner email_input = new Scanner(System.in);
String email = email_input.next();
p1.setEmail(email);
catalog.add(email);
System.out.println("You inserted the following e-mail: "+p1.getEmail());
System.out.println("Εισάγετε την ημερομηνία γέννησης:");
Scanner date_of_birth_input = new Scanner(System.in);
String date_of_birth = date_of_birth_input.nextLine();
p1.setDate_of_birth(date_of_birth);
catalog.add(date_of_birth);
System.out.println("You inserted the following: "+p1.getDate_of_birth());
System.out.println("Εισάγετε τον αριθμό ΑΜΚΑ:");
Scanner AMKA_input = new Scanner(System.in);
String AMKA = AMKA_input.next();
p1.setAMKA(AMKA);
catalog.add(AMKA);
System.out.println("You inserted the following ΑΜΚΑ: "+p1.getAMKA());
}
}
}
static void showMenu(){
System.out.println("1. View the whole contacts");
System.out.println("2. Insert a new contact");
System.out.println("Please give your choice");
}
}
and my personnel class with getter and setter methods in order to store the data from user input,
package com.andrekreou;
import java.io.Serializable;
public class Personnel implements Serializable {
private String full_name;
private String phone_number;
private String address;
private String email;
private String date_of_birth;
private String AMKA;
public String getFull_name() {
return full_name;
}
public void setFull_name(String full_name) {
this.full_name = full_name;
}
public String getPhone_number() {
return phone_number;
}
public void setPhone_number(String phone_number) {
this.phone_number = phone_number;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getDate_of_birth() {
return date_of_birth;
}
public void setDate_of_birth(String date_of_birth) {
this.date_of_birth = date_of_birth;
}
public String getAMKA() {
return AMKA;
}
public void setAMKA(String AMKA) {
this.AMKA = AMKA;
}
}
My problem is that I want to use the catalog list in option 1 using a foreach loop but I can't since I am getting a "Cannot resolve symbol catalog" error as showing in the code. What am I doing wrong?
I am not going to argue about the correctness of the solution, and the different way to implement it. However, if you want to solve that compilation error, it is just a matter of variable scope: You just need to move the creation of the catalog list at the beginning of the main function, in a way to increase its scope, for example you can put it as first statement, like this:
public class Main {
public static void main(String[] args) {
ArrayList<String> catalog = new ArrayList<>(); // Creation of catalog list
...
}
...
}

How can I assign data from a file to an array

I have a file, which looks like follows:
Barack Obama 3
Michael Jackson 1
Dua Lipa 2
... all of 15 lines
I need to read from a file and place names in a one-dimensional array and integers into another, then sort everything from smallest int to biggest.
I was looking for help everywhere, I tried to google it and looked through many articles. I couldn't find the answer. That's what I tried but I know it's wrong.
import java.io.File;
import java.util.Scanner;
public class Boombastic {
public static void main(String[] args) throws Exception {
File file = new File("C:\\Users\\bobo\\Documents\\NetBeansProjects\\" + "boombastic\\boombastic.txt");
String[] fullName;
Scanner sc = new Scanner(file);
while (sc.hasNext()) {
fullName[] = sc.next();
}
}
}
Could you please help me to fix it?
Use scanner.nextLine().
Also, I recommend using ArrayList because you don't know how many lines scanner has. If you do, then you can keep using arrays.
Using ArrayList:
public class Boombastic {
public static void main(String[] args) throws Exception {
File file = new File("C:\\Users\\bobo\\Documents\\NetBeansProjects\\" + "boombastic\\boombastic.txt");
ArrayList<String> fullName = new ArrayList<>();
ArrayList<Integer> ints = new ArrayList<>();
Scanner sc = new Scanner(file);
Scanner sc2 = new Scanner(file); // For the integers.
while(sc.hasNext()) {
fullName.add(sc.nextLine());
ints.add(sc2.nextInt());
}
}
}
Using arrays (assuming the scanner has 3 lines):
public class Boombastic {
public static void main(String[] args) throws Exception {
File file = new File("C:\\Users\\bobo\\Documents\\NetBeansProjects\\" + "boombastic\\boombastic.txt");
String[] fullName = new String[3];
int[] ints = new int[3];
Scanner sc = new Scanner(file);
Scanner sc2 = new Scanner(file);
int i = 0;
while (sc.hasNext()) {
fullName[i ++] = sc.next();
ints[i ++] = sc2.nextInt();
}
}
}
And to sort it, do
Arrays.sort(fullName);
Arrays.sort(ints);
This isn't the most efficient method, since it uses two scanners, but it works.
Instead of trying to assign the data to an array using separators and stuff, it is better to read all lines in a String and then process this String. There are plenty ways of how to read the lines of a text file into a String. Some basic of them can be found in this question.
However, I would not split the data and "store" them into Arrays since you do not know how much your data is. Also, I would choose "a more object oriented programming way" to achieve it. I would create a class, and objects of it will represent this data. After that I'd add these objects to collection and use Java's APIs to sort it within one line.
Finally, instead of new File("C:\\Users\\bobo\\Documents\\NetBeansProjects\\" + "boombastic\\boombastic.txt"); use File class constructor to build the path. Messing with separators is yikes...
An example would be:
public class Boombastic {
public static class Person {
private String firstName, lastName;
private int id; // ??
public Person(String firstName, String lastName, int id) {
this.firstName = firstName;
this.lastName = lastName;
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Override
public String toString() {
return "Person [firstName=" + firstName + ", lastName=" + lastName + ", id=" + id + "]";
}
}
public static void main(String[] args) throws Exception {
File desktop = new File(System.getProperty("user.home"), "Desktop");
File textFileWithData = new File(desktop, "data.txt");
List<Person> persons = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(textFileWithData))) {
String line = br.readLine();
while (line != null) {
String[] lineSplit = line.split("\\s");
Person person = new Person(lineSplit[0], lineSplit[1], Integer.parseInt(lineSplit[2]));
persons.add(person);
line = br.readLine();
}
} catch (IOException e) {
System.err.println("File cannot be read.");
e.printStackTrace();
System.exit(0);
}
// print unsorted
persons.forEach(System.out::println);
Collections.sort(persons, (p1, p2) -> p1.getId() - p2.getId()); // Sort persons by ID
System.out.println();
// print sorted
persons.forEach(System.out::println);
}
}
If you are having hard time to understand the sort part, take a look at how to use comparator in java.
My text file:
John Doe 3
Someone Else 2
Brad Pitt 5
Kevin Spacey 1
Output:
Person [firstName=John, lastName=Doe, id=3]
Person [firstName=Someone, lastName=Else, id=2]
Person [firstName=Brad, lastName=Pitt, id=5]
Person [firstName=Kevin, lastName=Spacey, id=1]
Person [firstName=Kevin, lastName=Spacey, id=1]
Person [firstName=Someone, lastName=Else, id=2]
Person [firstName=John, lastName=Doe, id=3]
Person [firstName=Brad, lastName=Pitt, id=5]

How to create a search method for an array

My code is as follows:
import java.io.*;
import java.util.*;
public class readStudents extends Object
{
private String SName = "";
private String DoB = "";
private String Gender = "";
private String Address = "";
Student [] students = new Student[20];
public void fillStudentArray()
{
// properties
int size; // total number of Students in collection
File file = new File("StudentDetails.txt");
try
{
Scanner in = new Scanner(file);
while(in.hasNextLine())
{
String SName = in.next();
String DoB = in.next();
String Gender = in.next();
String Address = in.next();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
public String getName()
{
return this.SName;
}
public void printname()
{
System.out.println("hello");
}
public Student search(String name)
{
System.out.print("Enter the name you wish to search: ");
for (int i = 0; i < this.students.length; i++)
{
Student s = this.students[i];
if (s.getName().equalsIgnoreCase(name))
{
return s;
}
}
return null;
}
} //end class students
However I am trying to create a well refined program that I can call on these methods from another main file with as minimal code as possible in that file.
The search method at the bottom is tripping me up as I am assuming I need to put something to do with the array in my getName() method but I can't figure it out.
Since I am doing this as a class for another main method, with the placement of my array initialization and declaration it allows the other methods to access it but it leaves me with no way to create this array from the main method unless I am missing something?
This is the error jCreator is throwing:
F:\University\Ass2\readStudents.java:62: error: cannot find symbol
if (s.getName().equalsIgnoreCase(name))
^
symbol: method getName()
location: variable s of type Student
You never populated the Student students[] array... You retrieved the values you would populate them with here:
while(in.hasNextLine())
{
String SName = in.next();
String DoB = in.next();
String Gender = in.next();
String Address = in.next();
}
But you never actually set those values into a Student object in the students[] array
Do something like this:
int i = 0;
while(in.hasNextLine())
{
String name = in.next();
String dateOfBirth = in.next();
String gender = in.next();
String address = in.next();
students[i] = new Student(name, dateOfBirth, gender, address);
i++
}
Also, you might consider ditching the array and using some sort of List or Hash object... If your file contains more than 20 lines, the array will be out of index when you try to define the 21st value.. With an arraylist or a List you wouldn't have that problem
I took a liberty to tweak your code as previous answer mentioned, it's better to use array list in your case. You could make a small student container class within your reader. The get name method is also kinda redundant ;s
package test;
import java.io.*;
import java.util.*;
public class readStudents{
ArrayList<Student> students = new ArrayList<Student>();
class Student {
private String name;
private String dob;
private String gender;
private String address;
public Student(String name, String dob, String gender, String address) {
this.name = name;
this.dob = dob;
this.gender = gender;
this.address = address;
}
public void fillStudentArray() {
// properties
int size; // total number of Students in collection
File file = new File("StudentDetails.txt");
try {
Scanner in = new Scanner(file);
while (in.hasNextLine()) {
String SName = in.next();
String DoB = in.next();
String Gender = in.next();
String Address = in.next();
students.add(new Student(SName, DoB, Gender, Address));
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public String getName(Student student) {
return student.name;
}
public void printname() {
System.out.println("hello");
}
public Student search(String name) {
System.out.print("Enter the name you wish to search: ");
for (Student student : students) {
if (student.name.equalsIgnoreCase(name))
;
return student;
}
return null;
}
}
}
If you're not forced by your teacher to use for or for-each cycle in the search function - this is how to do a full scan the Java 8 way
public Optional<Student> findFirstByName(final String name) {
return Arrays.stream(students)
.filter(s -> s.getName().equalsIgnoreCase(name))
.findFirst();
}

Printing string arrays to a text file using java

I am trying to print out the results of the users inputs to a simple text file but everything I have tried has rendered unsuccessful. I tried using a PrintWriter within the switch case but the results still just printed out null. I am quite new to Java so maybe I am missing obvious?
Here is the code:
package parkingsystem;
import java.io.*;
import java.util.Scanner;
public class Registration {
static String [][] userData;
static String [][] fileData;
public static void Registration(){
Scanner input = new Scanner(System.in);
String lotNo;
String First;
String Last;
String studentID;
String phoneNo;
String email;
String carNo;
String dateReg;
String strcontent;
String proceed;
boolean proceed2 = true;
userData = new String [50][6];
fileData = new String [50][6];
int counter = 0;
int col;
int row;
boolean carry_on = true;
MainMenu choices = new MainMenu();
while(proceed2=true){
System.out.println("Press Y/y to add a new user");
System.out.println("Press N/n to return to menu");
proceed = input.nextLine();
switch (proceed) {
case "Y":
case "y":
System.out.println("Enter your student ID");
studentID = input.nextLine();
System.out.println("Enter your first name");
First = input.nextLine();
System.out.println("Enter your last name");
Last = input.nextLine();
System.out.println("Enter your car number");
carNo = input.nextLine();
System.out.println("Enter your contact number");
phoneNo = input.nextLine();
System.out.println("Enter your email address");
email = input.nextLine();
row = counter ;
userData [row][0] = studentID;
userData [row][1] = First;
userData [row][2] = Last;
userData [row][3] = carNo;
userData [row][4] = phoneNo;
userData [row][5] = email;
if (counter == 6){
carry_on=false;
}
proceed2 = false;
break;
case "N":
case "n":
choices.Menus();
break;
}
}
}
}
Here's a second pass at re-factoring your code.
So now in this refactoring we capture and store the newly created CarOwner objects and store them in a list.
Then we see how to go through that List of CarOwner's and then write those objects to a file called carOwners.dat
Ordinarily, in industry, code re-factoring is done in the context of having a set of unit tests against which you can ensure that the refactoring hasn't broken the required behaviour of the code but we are just learning here so this work serves to explain some of the concepts that you are missing and this first pass iteration below has some issues of its own so don't take this as the final product.
Refactorings
I have created a CarOwner class.
I have renamed the Boolean variable canProceed so that it reads more naturally.
Update : I have made the CarOwner class Serializable; this will allow us to write the Object to a File.
Update : I have added code that up the new CarOwners and adds it to a List and then I iterate over the list to write those CarOwner objects to a FileStream.
package parkingsystem;
import java.io.FileNotFoundException;
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.io.FileOutputStream;
import java.util.Scanner;
public class Registration {
public static void main(String[] args) {
List carOwners = new ArrayList();
Scanner input = new Scanner(System.in);
boolean canProceed = true;
while (canProceed) {
System.out.println("Press Y/y to add a new user");
System.out.println("Press N/n to return to menu");
String optionRequested = input.nextLine();
if (optionRequested.equalsIgnoreCase("Y")) {
CarOwner owner = new CarOwner();
System.out.println("Enter your student ID");
owner.setStudentID(input.nextLine());
System.out.println("Enter your first name");
owner.setFirst(input.nextLine());
System.out.println("Enter your last name");
owner.setLast(input.nextLine());
System.out.println("Enter your car number");
owner.setCarNo(input.nextLine());
System.out.println("Enter your contact number");
owner.setContactNumber(input.nextLine());
System.out.println("Enter your email address");
owner.setEmail(input.nextLine());
owner.setDateReg(new Date().toString());
carOwners.add(owner);
} else if (optionRequested.equals("N") || optionRequested.equals("n")) {
canProceed = false;
}
}
ObjectOutputStream objectWriter = null;
for (CarOwner carOwner : carOwners) {
try {
objectWriter = new ObjectOutputStream(new FileOutputStream("carOwners.dat"));
objectWriter.writeObject(carOwner);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Here's what the CarOwner class now looks like ...
package parkingsystem;
import java.io.Serializable;
public class CarOwner implements Serializable{
private String First;
private String Last;
private String studentID;
private String email;
private String carNo;
private String dateReg;
private String contactNumber;
public CarOwner() {
}
public String getFirst() {
return First;
}
public void setFirst(String first) {
First = first;
}
public String getLast() {
return Last;
}
public void setLast(String last) {
Last = last;
}
public String getStudentID() {
return studentID;
}
public void setStudentID(String studentID) {
this.studentID = studentID;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCarNo() {
return carNo;
}
public void setCarNo(String carNo) {
this.carNo = carNo;
}
public String getDateReg() {
return dateReg;
}
public void setDateReg(String dateReg) {
this.dateReg = dateReg;
}
public void setContactNumber(String contactNumber) {
this.contactNumber = contactNumber;
}
public String getContactNumber() {
return contactNumber;
}
#Override
public String toString() {
return "CarOwner{" +
"First='" + First + '\'' +
", Last='" + Last + '\'' +
", studentID='" + studentID + '\'' +
", email='" + email + '\'' +
", carNo='" + carNo + '\'' +
", dateReg='" + dateReg + '\'' +
", contactNumber='" + contactNumber + '\'' +
'}';
}
}
Ok so creating the CarOwner class is done to make a start at making this code more object oriented.
Secondly the re-factored code demonstrates correct use of a Boolean variable in Java.
As the other commentators have already pointed out the assignment operator = is easily confused with the test for Boolean equality. See Java Operators
Also I have renamed Boolean proceed; to be Boolean canProceed; This is a common strategy. Naming a Boolean variable to read as a question to which the "answer" is, yes or no, or True or False.
This then means we can write code like while(canProceed) which reads very easily. See also if statement on the Java tutorial
I hope this helps.

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