Searching address book for info - java

I am trying to make an address book that prompts you enter the first, last, street address, city, State, and zip code for three people.
Then be able to search for any of the info the user inputs and then display all of the info for that person.
I have managed to get it to prompt the user for adding the info but I can't seem to figure out how to search the arraylist for the info.
for (int count = 0; count < 3; count++)
{
aBook.add(new YAAddressBook());
aBook.get(count).addEntry();
System.out.println();
}
int foundIndex = YAAddressBook.search(aBook);
System.out.println();
if (foundIndex > -1)
aBook.get(foundIndex).display();
System.out.println("Found");
else
System.out.println("No Entry Found");
}
}//end YoungAndrewChapter10
import java.util.ArrayList;
import java.util.Scanner;
public class YAAddressBook
{
private static String first;
private static String last;
private static String choice;
private static String searchA;
private static Scanner keybd = new Scanner(System.in);
private String street;
private String cityState;
private String zip;
private int answer = 0;
public static int search(ArrayList<YAAddressBook> aBook)
{
System.out.print("Search Menu: \n1. Search First Name \n2. Search Last
Name\n3.Search Street Address \n4.Search City, State \n5.Search Zip Code \n\n");
System.out.print("Please Enter Field to Search: ");
choice = keybd.nextLine();
System.out.print("Please Enter Value to Search For: ");
searchA = keybd.nextLine();
switch (choice)
{
case "1":
break;
case "2":
break;
case "3":
break;
case "4":
break;
case "5":
break;
default:
break;
}
return -2;
}
public void addEntry()
{
YAAddressBook aBook = new YAAddressBook();
System.out.print("Please Enter First Name: ");
first = keybd.nextLine();
System.out.print("Please Enter Last Name: ");
last = keybd.nextLine();
System.out.print("Please Enter Street Address: ");
street = keybd.nextLine();
System.out.print("Please Enter City, State: ");
cityState = keybd.nextLine();
System.out.print("Please Enter Zip Code: ");
zip = keybd.nextLine();
}
}//end YAAdreesBook

Depending on the field chosen, you would have to loop throughout all the arraylist until you find the correct item, for example if FirstName is chosen:
for (int i = 0; i< addressbook.size(); i++)
{
if (addressbook.get(i).FirstName == "Tom" )
return addressbook.get(i);
}
return null;
this will return the first element that matches the search, or null if nothing matches.

Related

i need help in storing multiple user input into an array with maximum limitation and being able to call it later in the code

Im still learning java and i want to understand more about array. Im still in school and we were asked to create an asean phonebook which can store, edit, delete, and view/search the information that are inputted. Im still doing the storing of information block of code and im struggling how to save multiple input in an array that is limited only to 100 contacts and can be searched later in the code. Can someone help me with my task and make me understand??
import java.util.Scanner;
public class Phonebook
{
public static void main (String [] args)
{
Scanner input = new Scanner (System.in);
int i = 0;
String studentNumber, surName, firstName, occuPation, countryCode, areaCode, numBer;
char genDer;
do
{
Menu();
System.out.println(" ");
System.out.print("Go to: ");
String choice = input.next();
if (choice.equals("1") || choice.equals("2") || choice.equals("3") || choice.equals("4") || choice.equals("5"))
{
i++;
switch(choice)
{
case "1":System.out.println("Enter student number: ");
studentNumber = input.next();
System.out.println("Enter surname: ");
surName = input.next();
System.out.println("Enter first name: ");
firstName = input.next();
System.out.println("Enter occupation: ");
occuPation = input.next();
System.out.println("Enter gender (M for male, F for female): ");
genDer = input.next();
System.out.println("Enter counter code: ");
countryCode = input.next();
System.out.println("Enter area code: ");
areaCode = input.next();
System.out.println("Enter number: ");
numBer = input.next();
break;
case "2":System.out.println("2");break;
case "3":System.out.println("3");break;
case "4":System.out.println("4");break;
case "5":System.out.println("5");break;
}
}
else
{
System.out.println("Invalid keyword, Please try again");
}
}
while (i < 1);
}
static void Menu()
{
System.out.println("[1] Store to ASEAN phonebook");
System.out.println("[2] Edit entry in ASEAN phonebook");
System.out.println("[3] Delete entry from ASEAN phonebook");
System.out.println("[4] View\\search ASEAN phonebook");
System.out.println("[5] Exit");
}
}

How to alphabetize a phonebook in a string

I have my PhoneBook program but I am trying to get the entries to automatically be put in alphabetical order when the user enter "l" for the list of entries. I can't figure out though how to do that. I've tried putting it into a list a sorting it that way but it only takes the first name of the entry.
import java.io.*;
import java.util.*;
class Entry {
public String fname, number, note, lname;
}
public class Main {
public static Entry[] contactList;
public static int num_entries;
public static Scanner stdin = new Scanner(System.in);
public static void main(String args[]) throws Exception{
int i; char C;
String code, Command;
contactList = new Entry[200];
num_entries = 0;
readPhoneBook("PhoneBook.txt");
System.out.println("Please Enter A Command.\nUse" +
" \"e\" for enter," +
" \"f\" for find," +
" \"l\" for listing all the entries," +
" \"m\" to merge duplicate entries," +
" \"d\" to delete an entry," +
" \"q\" to quit.");
Command = null;
C = ' ';
while(C != 'q'){
System.out.print("Command: ");
Command = stdin.next();
C = Command.charAt(0);
switch (C) {
case 'e': addContact(); break;
case 'f':
code = stdin.next();
stdin.nextLine();
i = index(code);
if (i >= 0) displayContact(contactList[i]);
else System.out.println("**No entry with code " + code); break;
case 'l':
listAllContacts(); break;
case 'q':
CopyPhoneBookToFile("PhoneBook1.txt");
System.out.println("Quitting the application. All the entries are "
+ "stored in the file PhoneBook1.txt"); break;
case 'm':
break;
case 'd':
break;
default:
System.out.println("Invalid command Please enter the command again");
}
}
}
public static void readPhoneBook(String FileName) throws Exception {
File F;
F = new File(FileName);
Scanner S = new Scanner(F);
while (S.hasNextLine()) {
contactList[num_entries]= new Entry();
contactList[num_entries].fname = S.next();
contactList[num_entries].lname = S.next();
contactList[num_entries].number = S.next();
contactList[num_entries].note = S.nextLine();
num_entries++;
}
S.close();
}
public static void addContact() {
System.out.print("Enter First Name: ");
String fname = stdin.next(); //First Name
stdin.nextLine();
System.out.print("Enter Last Name: ");
String lname = stdin.next(); //Last Name
String number;
stdin.nextLine();
contactList[num_entries] = new Entry();
contactList[num_entries].fname = fname; //Saves first name as fname
contactList[num_entries].lname = lname; //Saves last name as lname
System.out.print("Enter Number: ");
number = stdin.nextLine();
contactList[num_entries].number = number; //Saves phone number as number
System.out.print("Enter Notes: ");
contactList[num_entries].note = stdin.nextLine(); //saves any notes
num_entries++;
}
public static int index(String Key) {
// Function to get the index of a key from an array
// if not found, returns -1
for (int i=0; i < num_entries; i++) {
if (contactList[i].fname.equalsIgnoreCase(Key))
return i; // Found the Key, return index.
}
return -1;
}
public static void displayContact(Entry contact) {
System.out.println("--"+ contact.fname+"\t"+
contact.lname+"\t"+
contact.number+"\t"+
contact.note);
}
public static void listAllContacts() {
int i = 0;
while (i < num_entries) {
displayContact(contactList[i]);
i++;
}
}
public static void CopyPhoneBookToFile(String FileName) throws Exception{
FileOutputStream out = new FileOutputStream(FileName);
PrintStream P = new PrintStream( out );
for (int i=0; i < num_entries; i++) {
P.println(contactList[i].fname + "\t" + contactList[i].lname + "\t" + contactList[i].number +
"\t" + contactList[i].note);
}
}}
this is the bit for entering a new contact
public static void addContact() {
System.out.print("Enter First Name: ");
String fname = stdin.next(); //First Name
stdin.nextLine();
System.out.print("Enter Last Name: ");
String lname = stdin.next(); //Last Name
String number;
stdin.nextLine();
contactList[num_entries] = new Entry();
contactList[num_entries].fname = fname; //Saves first name as fname
contactList[num_entries].lname = lname; //Saves last name as lname
System.out.print("Enter Number: ");
number = stdin.nextLine();
contactList[num_entries].number = number; //Saves phone number as number
System.out.print("Enter Notes: ");
contactList[num_entries].note = stdin.nextLine(); //saves any notes
num_entries++;
}
I would make a compareTo method in your Entry class and set it up to compare how you want it to. The most important part would be how you store your Entries though. If you use a sorted array, you can just sort everything as you enter it into the array, and blast through linearly when you want to read it out

How to get a scanner to loop until it reads a desired string?

Scanner one = new Scanner(System.in);
System.out.print("Enter Name: ");
name = one.nextLine();
System.out.print("Enter Date of Birth: ");
dateofbirth = one.nextLine();
System.out.print("Enter Address: ");
address = one.nextLine();
System.out.print("Enter Gender: ");
gender = //not sure what to do now
Hi I've tried to figure this out myself but I can't quite get it from looking at other examples, most are either only accepting certain characters or A-Z+a-z
I'm trying to make the program only accept input of male or female ignoring the case and if the input is wrong to repeat the "Enter Gender:" until a correct value is entered.
You can put the piece of code in a while and validate each time. for instance:
String gender;
do
{
System.out.print("Enter Gender ('male' or 'female'): ");
gender = one.nextLine().toLowercase();
} while(!gender.equals("male") && !gender.equals("female"))
do {
System.out.print("Enter Gender (M/F): ");
gender = one.nextLine();
} while (!gender.equalsIgnoreCase("M") && !gender.equalsIgnoreCase("F"));
You can add an if check after gender assignment to display a invalid message
One way to do this is to use infinite loop and a label to break out.
Like this:
//Start
Scanner one = new Scanner(System.in);
here:
while (true){
System.out.print("Enter Gender: ");
String str = one.nextLine();
switch (str.toUpperCase()){
case "MALE":
System.out.println("Cool");
break here;
case "FEMALE":
System.out.println("Nice");
break here;
default:
System.out.println("Genders variants: Male/Female");
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Name: ");
String name = readValue(scanner, null);
System.out.print("Enter Date of Birth: ");
String dateofbirth = readValue(scanner, null);
System.out.print("Enter Address: ");
String address = readValue(scanner, null);
System.out.print("Enter Gender: ");
String gender = readValue(scanner, createGenderMatcher());
}
private static IMatcher createGenderMatcher() {
return new IMatcher() {
#Override
public boolean isMatch(String value) {
return "male".equalsIgnoreCase(value) || "female".equalsIgnoreCase(value);
}
};
}
private static String readValue(Scanner scanner, IMatcher matcher) {
String value = null;
do {
value = scanner.nextLine();
} while (matcher != null && !matcher.isMatch(value));
return value;
}
private interface IMatcher {
public boolean isMatch(String value);
}

How should I add a search method in this code

Scanner scanner = new Scanner(System.in);
int weight;
int age;
//arrays
List<String> last = new ArrayList<String>();
List<Integer> zage = new ArrayList<Integer>();
List<Integer> zweight = new ArrayList<Integer>();
int i = 0;
int userInput = 0;
//menu options
while(userInput != 2) {
userInput = scanner.nextInt(); // collects the user inputs
//several switch statements to answer each menu options
switch(userInput) {
case 1:
it saves and stores all the user inputs.
System.out.println("Enter a last name, age, weight"); //stores all the user information
String lastName = scanner.next();
last.add(lastName);
age = scanner.nextInt();
zage.add(age);
weight = scanner.nextInt();
zweight.add(weight);
break;
Need to add a search code where it will retrieve the user inputs and display it, but i'm not sure on how to do it.
case 5:
System.out.println("Enter the name; Enter DONE to exit");
System.out.println("FOUND!!! Last Name: " +last+ " Age: " +zage+ " Weight: " +zweight);
Your names are stored in a list so you can try this:
if (last.contains(searchName)) {
String foundName = last.get(last.indexOf(searchName));
System.out.println("FOUND!!! Last Name: " +foundName);
} else{
System.out.println("Last Name: " +searchName+ " NOT FOUND!!! ");
}
Note that duplicate names may be in the list so you may want to loop over the indexes.
you can do this:
String enteredLastName = scanner.next();
for (String name : last){
if (name.equals(enteredLastName ){
//do something
}
}

Programming "Add Method" array seems to not be working

Hi, I'm very new to java and I'm currently trying to create a student name and mark menu but I'm having trouble with my add method, I think it's something to do with my Arrays but I can't figure it out, any help would be appreciated.
Below is my unitResult method
public class UnitResults
{
private String unitTitle;
private String [] fName;
private String [] surname;
//private String [] UnitResults;
private int [] Marks;
private int Mark;
private int pointer ;
private static String course = "HND Computing";
public UnitResults(int Size,String title)
{
this.fName = new String [Size];
this.surname = new String [Size];
this.Marks = new int [Size];
pointer = 0;
fName[pointer] = "Daniel";
surname[pointer] = "Scullion";
Marks[pointer] = 60;
unitTitle = title;
pointer ++;
}
public Boolean add( String tempfName, String tempsName, int newGrade)
{
if (pointer == fName.length)
{
System.out.println("The Students Database is full");
return false;
}
else
{
fName [pointer] = tempfName;
surname [pointer] = tempsName;
Marks[pointer] = newGrade;
pointer ++;
return true;
}
}// end Add
but when I try to add this using a menu system below
int option = 0;
option = menuSystem();
while (option != 6)
{
System.out.println("");
switch(option)
{
case 1:
System.out.println(" Please Enter The Students First Name");
String tempfName = keyb.nextLine();
System.out.println("Please Enter The Students Last Name");
String tempsName = keyb.nextLine();
System.out.println(" Please Enter The Students Mark");
int newGrade = keyb.nextInt();
myUnit.add(tempfName, tempfName,newGrade);
break;
When I enter my option 1 the output that I get is :
Please Enter The Students First Name
Please Enter The Students Last Name
Any ideas what's wrong here been searching for a long time, probably something simple but I've no idea :/
Edit: below is my menu class
import java.util.Scanner;
public class MenuResults {
static Scanner keyb = new Scanner(System.in);
public static int menuSystem()
{
System.out.println("*********************************");
System.out.println(" ");
System.out.println("1.Add New Student");
System.out.println("2.Display Students Details");
System.out.println("3.Delete a Students");
System.out.println("4.Update Student Details");
System.out.println("5.Sort Students By Mark");
System.out.println("6.Sort Students By Surname");
System.out.println("7.Search For A Student");
System.out.println(" ");
System.out.println("**********************************");
System.out.print("\n Enter choice:");
int option = keyb.nextInt();
return option;
}
public static void main(String[] args) {
UnitResults myUnit = new UnitResults(3, "Java");
int option = 0;
option = menuSystem();
while (option != 6)
{
System.out.println("");
switch(option)
{
case 1:
System.out.println(" Please Enter The Students First Name");
String tempfName = keyb.nextLine();
System.out.println("Please Enter The Students Last Name");
String tempsName = keyb.nextLine();
System.out.println(" Please Enter The Students Mark");
int newGrade = keyb.nextInt();
myUnit.add(tempfName, tempsName,newGrade);
break;
case 2:
myUnit.display();
break;
case 3:
break;
case 4:
break;
case 5:
case 6:
break;
default:
System.out.println(" Invalid Entry");
}//end switch
}
}
}
There is my whole menu class as asked for.
EDIT: when I forget the user input and hard input it using: myUnit.add("John","tommy",12);
I get "Student Database is full" about one hundred times..
Wild guess, when you use your menu and type 1 then ENTER a carriage return (\n) for the ENTER is still present in your Scanner after nextInt() is called.
So next call to readLine() will use the \n (remaining ENTER) for the line and will not wait for user input.
Possible correction:
public static int menuSystem()
{
final Scanner keyb = new Scanner(System.in);
// ...
}
public static void main(String[] args) {
final UnitResults myUnit = new UnitResults(3, "Java");
int option = menuSystem();
while (option != 6) {
final Scanner keyb = new Scanner(System.in);
// ...
option = menuSystem();
}
}
And removal of the static kbd declaration
A better solution is to simply call keyb.nextLine() after calling keyb.nextInt() to handle the end of line token. Quite simply change this:
System.out.println(" Please Enter The Students Mark");
int newGrade = keyb.nextInt();
myUnit.add(tempfName, tempsName,newGrade);
to this:
System.out.println(" Please Enter The Students Mark");
int newGrade = keyb.nextInt();
keyb.nextLine(); // ****** add this *******
myUnit.add(tempfName, tempsName,newGrade);

Categories

Resources