How can I Enhance my AddressBook addEntry() method? - java

I have an Address Book Program that [1] adds Entry [2] delete entry [3] update/edit entry [4] view all entry and [5] view specific entry..
Entries were stored in an Array entry[] like:
entry[counter] = new AddressBookEntry();
It all runs properly but the thing is... i want there was a checking if the user's input name was already used or if the user doesn't typed anything when i ask "Enter Name: "
here's my addEntry() method:
public void addEntry() {
entry[counter] = new AddressBookEntry();
entry[counter].setName(JOptionPane.showInputDialog("Enter name: "));
entry[counter].setAdd(JOptionPane.showInputDialog("Enter add: "));
entry[counter].setPhoneNo(JOptionPane.showInputDialog("Enter Phone No.: "));
entry[counter].setEmail(JOptionPane.showInputDialog("Enter E-mail: "));
counter++;
}
It allows user input any Entry he likes... but no checking if the name is already used and if the user leave the "Enter Name: " blank it still allows the user to proceed to the "Enter Add.: "
here's my complete code in my main program:
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
public class AddressBook {
private AddressBookEntry entry[];
private int counter;
private String SName;
private int notfound = 0;
public static void main(String[] args) {
AddressBook a = new AddressBook();
a.entry = new AddressBookEntry[100];
int option = 0;
try {
while (option != 5) {
String content = "Choose an Option\n\n"
+ "[1] Add an Entry\n"
+ "[2] Delete an Entry\n"
+ "[3] Update an Entry\n"
+ "[4] View all Entries\n"
+ "[5] View Specific Entry\n"
+ "[6] Exit";
option = Integer.parseInt(JOptionPane.showInputDialog(content));
switch (option) {
case 1:
a.addEntry();
break;
case 2:
a.deleteEntry();
break;
case 3:
a.editEntry();
break;
case 4:
a.viewAll();
break;
case 5:
a.searchEntry();
break;
case 6:
System.exit(1);
break;
default:
JOptionPane.showMessageDialog(null, "Invalid Choice!");
}
}
}catch(NumberFormatException e){
JOptionPane.showMessageDialog(null, "Please Choose a Number in the displayed Menu");
}
}
public void addEntry() {
entry[counter] = new AddressBookEntry();
entry[counter].setName(JOptionPane.showInputDialog("Enter name: "));
entry[counter].setAdd(JOptionPane.showInputDialog("Enter add: "));
entry[counter].setPhoneNo(JOptionPane.showInputDialog("Enter Phone No.: "));
entry[counter].setEmail(JOptionPane.showInputDialog("Enter E-mail: "));
counter++;
}
public void viewAll() {
String addText = " NAME\tADDRESS\tPHONE NO.\tE-MAIL ADD\n\n";
int nonNull = 0;
for (int i = 0; i < entry.length; i++) {
if (entry[i] != null) {
addText = addText + entry[i].getInfo() + "\n";
nonNull++;
}
if (nonNull == counter) {
break;
}
}
JOptionPane.showMessageDialog(null, new JTextArea(addText));
}
public void searchEntry() {
SName = JOptionPane.showInputDialog("Enter Name to find: ");
searchMethod();
}
public void searchMethod() {
for (int i = 0; i < counter; i++) {
if (entry[i].getName().equals(SName)) {
JOptionPane.showMessageDialog(null, entry[i].getInfo2());
notfound = 0;
break;
} else {
notfound++;
}
}
if (notfound != 0) {
JOptionPane.showMessageDialog(null, "Name Not Found!");
}
}
public void editEntry() {
SName = JOptionPane.showInputDialog("Enter Name to edit: ");
for (int i = 0; i < counter; i++) {
if (entry[i].getName().equals(SName)) {
entry[i] = new AddressBookEntry();
entry[i].setName(JOptionPane.showInputDialog("Enter new name: "));
entry[i].setAdd(JOptionPane.showInputDialog("Enter new add: "));
entry[i].setPhoneNo(JOptionPane.showInputDialog("Enter new Phone No.: "));
entry[i].setEmail(JOptionPane.showInputDialog("Enter new E-mail: "));
notfound = 0;
break;
} else {
notfound++;
}
}
if (notfound != 0) {
JOptionPane.showMessageDialog(null, "Name Not Found!");
}
}
public void deleteEntry() {
SName = JOptionPane.showInputDialog("Enter Name to delete: ");
for (int i = 0; i < counter; i++) {
if (entry[i].getName().equals(SName)) {
JOptionPane.showMessageDialog(null, "Found!");
entry[i] = null;
break;
}
}
}
}
Hope you can can help me I am new in Java and I really don't what to add in my code for checking.
* What should I add in my addEntry() method to check if the name was already used or no name entered?
* Do I need a condition like in my searchMethod()?

An address book tends to be a thing where given a name, you look up an address, and other information.
so this falls under a general pattern where you have a Key (the name) and a value (the other information)
When ever you see this, you want to think of using a Map
So, i'd recommend instead of putting your AddressBookEntry's in an array, use a map like this
Map<String, AddressBookEntry> addressBook = new HashMap<String, AddressBookEntry>();
then when you want to add a new entry do
addressBook.put("John", new AddressBookEntry());
the nice thing about a map is that you can only have one entry for the same person.
So you don't have to worry about what happens if you put John in the book twice. It will only allow one in there.

Related

Making the first input save in a folder first and then reference it

I need my program to detect previous entries in it's contact list and negate the user from inputting two identical entries. I keep trying, but I either allow every entry, or the entry that's invalid is still saved to my list.
What I want is to make it so my program will be a phone book, and no two people in real life should have the same number. This is why I want there to be only one contact with any given number.
Here's my code for checking the entry:
System.out.print("Enter Number: ");
number = stdin.nextLine(); // read the number
while(!number.matches(pattern)) { // as long as user doesnt enters correct format, loop
System.out.println("Error!");
System.out.println("Not proper digit format! Use \"012-3456\", \"(012)345-6789\"" +
", or \"012-345-6789\" format.");
System.out.print("Enter number: ");
number = stdin.nextLine();
}
for (Entry e : contactList) {
if (e.number.equals(number)) {
System.out.println("This phone number already exist. Please check contacts.");
System.out.println("");
return;
}else{
break;
}
}
contactList[num_entries].number = number;
Here's my full code for reference:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Scanner;
class Entry {
public String fname, lname, number, note;
}
class PBN {
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{
Scanner s = new Scanner(System.in);
int i;
char C;
String code, Command;
contactList = new Entry[999];
num_entries = 0;
try {
readPhoneBook("PhoneBook.txt");
} catch (FileNotFoundException e) {}
System.out.println("Codes are entered as 1 to 8 characters.\n" +
"Use Commands:\n" +
" \"e\" for enter a new contact,\n" +
" \"f\" for find contact by fist name,\n" +
" \"r\" for find contact by last name,\n" +
" \"y\" for find contact by phone number,\n" +
" \"l\" for listing all the existing contacts,\n" +
" \"d\" for removing contacts by phone number,\n" +
" \"a\" for sort alphabetically by first name,\n" +
" \"n\" for sort alphabetically by last name,\n" +
" \"p\" for sort by number,\n" +
" \"q\" to quit.");
Command = null;
C = ' ';
while(true) { // loop infinitely
System.out.print("Command: ");
Command = stdin.nextLine();
C = Command.charAt(0);
switch (C) {
case 'e': addContact(); break;
case 'f':
System.out.print("Search for contact by first name: ");
code = stdin.next();
stdin.nextLine();
index(code); break;
case 'r':
System.out.print("Search for contact by last name: ");
code = stdin.next();
stdin.nextLine();
index1(code); break;
case 'y':
System.out.print("Search for contact by phone number: ");
code = stdin.next();
stdin.nextLine();
index2(code); break;
case 'l':
listAllContacts(); break;
case 'q': // when user wants to quit
CopyPhoneBookToFile("PhoneBook.txt");
System.out.println("Quitting the application. All the entries are "
+ "stored in the file PhoneBook1.txt");
System.exit(0); // simply terminate the execution
case 'a':
sortList1();
break;
case 'n':
sortList2();
break;
case 'p':
sortListByPhoneNumber();
break;
case 'd': // m for deleting a contact; delete by phone number
System.out.print("Enter the phone number of a contact you wish to delete : ");
String number = stdin.nextLine();// read the contact number
removeEntry1(number); // remove the number from the entries
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.nextLine();
String lname;
String number;
String pattern = "^\\(?(\\d{3})?\\)?[- ]?(\\d{3})[- ](\\d{4})$";
while (fname.length() > 8 || fname.length() < 1) {
System.out.println("First name must be between 1 to 8 characters.");
System.out.print("Enter first name: ");
fname = stdin.nextLine();
}
contactList[num_entries] = new Entry();
contactList[num_entries].fname = fname;
System.out.print("Enter last name: ");
lname = stdin.nextLine();
while (lname.length() > 8 || lname.length() < 1) {
System.out.println("First name must be between 1 to 8 characters.");
System.out.print("Enter first name: ");
lname = stdin.nextLine();
}
contactList[num_entries].lname = lname;
System.out.print("Enter Number: ");
number = stdin.nextLine(); // read the number
while(!number.matches(pattern)) { // as long as user doesnt enters correct format, loop
System.out.println("Error!");
System.out.println("Not proper digit format! Use \"012-3456\", \"(012)345-6789\"" +
", or \"012-345-6789\" format.");
System.out.print("Enter number: ");
number = stdin.nextLine();
for (Entry e : contactList) {
if (e.number.equals(number)) {
System.out.println("This phone number already exist. Please check contacts.");
System.out.println("");
break;
} else {
return;
}
}
}
contactList[num_entries].number = number;
System.out.print("Enter Notes: ");
contactList[num_entries].note = stdin.nextLine();
num_entries++;
System.out.println();
}
public static void listAllContacts() {
for(Entry e : contactList) {
if(e != null)
displayContact(e);
else
break;
}
}
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)) {
if (i >= 0) displayContact(contactList[i]);
//return i;
} // Found the Key, return index.
}
return -1;
}
public static int index1(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].lname.equalsIgnoreCase(Key)) {
if (i >= 0) displayContact(contactList[i]);
//return i;
} // Found the Key, return index.
}
return -1;
}
public static int index2(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].number.equalsIgnoreCase(Key)) {
if (i >= 0) displayContact(contactList[i]);
//return i;
} // Found the Key, return index.
}
return -1;
}
public static void displayContact(Entry contact) {
System.out.println("--"+ contact.fname+"\t");
System.out.println("--"+ contact.lname+"\t");
System.out.println("--"+ contact.number+"\t");
System.out.println("--"+ contact.note);
System.out.println("");
}
public static void sortList1() {
int i;
Entry temp;
temp = new Entry();
for (int j = 0; j< num_entries; j++) {
for (i = j + 1; i < num_entries; i++) {
if (contactList[j].fname.compareToIgnoreCase(contactList[i].fname)> 0) {
temp = contactList[j];
contactList[j] = contactList[i];
contactList[i] = temp;
}
}
}listAllContacts();
}
public static void sortList2() {
int i;
Entry temp;
temp = new Entry();
for (int j = 0; j< num_entries; j++) {
for (i = j + 1; i < num_entries; i++) {
if (contactList[j].lname.compareToIgnoreCase(contactList[i].lname)> 0) {
temp = contactList[j];
contactList[j] = contactList[i];
contactList[i] = temp;
}
}
}listAllContacts();
}
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);
}
}
public static void removeEntry1(String number) {
Entry[] newcontactList = new Entry[contactList.length];
int i = 0;
for(Entry e : contactList) {
if(e == null) break; // if an entry is null then break the loop
if(e.number.equals(number)) // if the given number matches the current number
continue; // then skip
newcontactList[i++] = e;
}
num_entries--; // decrease the number of entries by 1;
contactList = newcontactList;
}
public static void sortListByPhoneNumber() {
int i;
Entry temp;
for (int j = 0; j < num_entries; j++) {
for (i = j + 1; i < num_entries; i++) {
if (contactList[j].number.compareToIgnoreCase(contactList[i].number) > 0) {
temp = contactList[j];
contactList[j] = contactList[i];
contactList[i] = temp;
}
}
}
listAllContacts();
}
}
The problem is that while you are looping through your contactList in for (Entry e : contactList) you are not checking the whole list!
E.g. if in the first cycle e.number doesn't equal the new number it goes to else statement and breaks the loop, then it goes and calls contactList[num_entries].number = number; saving potentially the already existing number;
To fix your code with minimum changes - just remove the else{ break;}
If you want a safer and more performant solution, use HashSet data structure for your contactList or TreeSet if you want it to be sorted - it will make sure that you will never have a duplicate entry, you can use Set.contains(number) to check if the entry already exists, and additionally HashSet will improve the complexity of entry lookups to O(1), TreeSet slightly worse O(logn) - either better then looping through the whole array which is O(n).
One way you can do that by using a boolean
boolean isPresent = false;
for (Entry e : contactList) {
if (e.number.equals(number)) {
System.out.println("This phone number already exist. Please check contacts.");
System.out.println("");
isPresent = true;
break;
}
}
Now check if the variable changed or not and do the entry
if (!isPresent) {
contactList[num_entries].number = number;
//rest of code
}
In Java 8 you could use optional
Optional<String> presentPh = Arrays.stream(contactList).filter(e -> e.number.equals(number)).findAny();
Now check if you find anything in filter
if (!presentPh.isPresent()) {
contactList[num_entries].number = number;
//rest of code
}

Counting occurrence of attributes inside the objects of a Java Array

I have created an array of 25 Flower objects. Each flower object holds the flower name(String), flower color(String), presence of thorns(boolean), and flower scent(String). These attributes are handled by the 'Flower' class. I have pasted both classes in case the error is being caused by either class. The user inputs all of the attributes of the flowers when the menu prompts for the information. After the user enters all of the flowers they want to, I need to be able to print out the entire array and a counter of how many of each flower there are. For instance, if the user puts in 10 flowers and there are 3 Roses, 2 Lilly's, 3 Dandelions, and 2 Orchids, I need to print the entire array and then print the number each flower was present. The format for the display is:
Flower name: Rose Flower color: Red Flower has thorns: true Flower scent: Sweet
Rose - 3
Lilly - 3
Dandelion - 3
Orchid - 2
I am able to print out the array as shown, but cannot get the count variable to work properly. I do not need to sort this array.
Another issue I am getting in an OutOfBounds error. I can only put in 24 flowers before I encounter this error. The 25th flower triggers it. I thought this was covered by the addFlower index counter, but obviously, I was incorrect.
This assignment does not allow the use of ArrayList, which would make this much simpler. We have not explored error handling yet either.
Current code is:
package assignment2;
import java.util.Scanner;
public class Assignment2
{
public static void main(String[] args)
{
new Assignment2();
}
public Assignment2()
{
Scanner input = new Scanner(System.in);
Flower flowerPack[] = new Flower[25];
System.out.println("Welcome to my flower pack interface.");
System.out.println("Please select a number from the options below");
System.out.println("");
while (true)
{
// Give the user a list of their options
System.out.println("1: Add an item to the pack.");
System.out.println("2: Remove an item from the pack.");
System.out.println("3: Search for a flower.");
System.out.println("4: Display the flowers in the pack.");
System.out.println("0: Exit the flower pack interfact.");
// Get the user input
int userChoice = input.nextInt();
switch (userChoice)
{
case 1:
addFlower(flowerPack);
break;
case 2:
removeFlower(flowerPack);
break;
case 3:
searchFlowers(flowerPack);
break;
case 4:
displayFlowers(flowerPack);
break;
case 0:
System.out.println("Thank you for using the flower pack interface. See you again soon!");
input.close();
System.exit(0);
}
}
}
private void addFlower(Flower flowerPack[])
{
String flowerName; // Type of flower
String flowerColor; // Color of the flower
Boolean hasThorns = false; // Have thorns?
String flowerScent; // Smell of the flower
int index = 0;
Scanner input = new Scanner(System.in);
System.out.println("What is the name of flower is it?");
flowerName = input.nextLine();
System.out.println("What color is the flower?");
flowerColor = input.nextLine();
System.out.println("Does the flower have thorns?");
System.out.println("Choose 1 for yes, 2 for no");
int thorns = input.nextInt();
if(thorns == 1)
{
hasThorns = true;
}
input.nextLine();
System.out.println("What scent does the flower have?");
flowerScent = input.nextLine();
Flower fl1 = new Flower(flowerName, flowerColor, hasThorns, flowerScent);
for(int i = 0; i < flowerPack.length; i++)
{
if(flowerPack[i] != null)
{
index++;
if(index == flowerPack.length)
{
System.out.println("The pack is full");
}
}
else
{
flowerPack[i] = fl1;
break;
}
}
}
private void removeFlower(Flower flowerPack[])
{
Scanner input = new Scanner(System.in);
System.out.println("What student do you want to remove?");
displayFlowers(flowerPack);
System.out.println("Choose 1 for the first flower, 2 for the second, etc" );
int index = input.nextInt();
index = index - 1;
for (int i = 0; i < flowerPack.length - 1; i++)
{
if(flowerPack[i] != null && flowerPack[i].equals(flowerPack[index]))
{
flowerPack[i] = flowerPack[i + 1];
}
}
}
private void searchFlowers(Flower flowerPack[])
{
Scanner input = new Scanner(System.in);
String name;
System.out.println("What flower would you like to search for?");
name = input.nextLine();
boolean found = false;
for (int i = 0; i < flowerPack.length; i++)
{
if (flowerPack[i].getFlowerName().equalsIgnoreCase(name))
{
found = true;
break;
}
}
if (found)
{
System.out.println("We found your flower.");
}
else
{
System.out.println("That flower was not found.");
}
}
private void displayFlowers(Flower flowerPack[])
{
int count = 1;
for(int i = 0; i < flowerPack.length; i++)
{
if (flowerPack[i] != null)
{
if (flowerPack[i].equals(flowerPack[i+1]))
{
count++;
}
else
{
System.out.println(flowerPack[i]);
count = 1;
}
}
else
{
if (flowerPack[i] == null)
{
break;
}
}
}
}
}
The Flower class is below.
package assignment2;
public class Flower
{
#Override
public String toString()
{
return "Flower name: " + this.getFlowerName() + "\t" +
"Flower color: " + this.getFlowerColor() + "\t" +
"Flower has thorns: " + this.getHasThorns() + "\t" +
"Flower scent: " + this.getFlowerScent() + "\t" ;
}
private String flowerName;
private String flowerColor;
private Boolean hasThorns;
private String flowerScent;
Flower(String flowerName, String flowerColor, Boolean hasThorns, String flowerScent)
{
this.flowerName = flowerName;
this.flowerColor = flowerColor;
this.hasThorns = hasThorns;
this.flowerScent = flowerScent;
}
String getFlowerName()
{
return flowerName;
}
private void setFlowerName(String flowerName)
{
this.flowerName = flowerName;
}
private String getFlowerColor()
{
return flowerColor;
}
private void setFlowerColor()
{
this.flowerColor = flowerColor;
}
private Boolean getHasThorns()
{
return hasThorns;
}
private void setHasThorns()
{
this.hasThorns = hasThorns;
}
private String getFlowerScent()
{
return flowerScent;
}
private void setFlowerScent()
{
this.flowerScent = flowerScent;
}
}
private void displayFlowers(Flower flowerPack[])
{
String[] usedNames = new String[flowerPack.length];
int[] nameCounts = new int[flowerPack.length];
int usedNamesCount = 0;
for (int i = 0; i < flowerPack.length; i++)
{
Flower flower = flowerPack[i];
if (flower == null)
{
continue;
}
int nameIndex = -1;
for (int j = 0; j < usedNamesCount; j++)
{
String usedName = usedNames[j];
if (flower.getFlowerName().equals(usedName))
{
nameIndex = j;
break;
}
}
if (nameIndex != -1)
{
nameCounts[nameIndex] += 1;
}
else
{
usedNames[usedNamesCount] = flower.getFlowerName();
nameCounts[usedNamesCount] += 1;
usedNamesCount++;
}
}
for (int i = 0; i < usedNamesCount; i++)
{
System.out.println(usedNames[i] + "s - " + nameCounts[i]);
}
}

Creating a library with book objects and member objects

I've just started programming recently and have ran into a few minor errors. I'm creating a library object which holds references to book objects and member objects, however I'm having trouble accessing methods from the member class and using them in the library class without errors popping up in the LibraryTester class. This is what I've coded
Library class
package assignment;
import java.nio.channels.MembershipKey;
import java.util.ArrayList;
import java.util.Scanner;
import org.omg.Messaging.SyncScopeHelper;
public class Library {
// Declared an array list of type book
private ArrayList<Book> Books;
private MemberList members;;
public Library(ArrayList<Book> Books, Member member) {
this.Books = Books;
this.members=members;
};
public void displayBooks() {
System.out.println("\t\t\t-----The Current Books in the library are-----");
for (int i = 0; i < Books.size(); i++) {
System.out.println("\n" + "\t\t" + Books.get(i).getTitle() + "\t\t\t" + "\n\t\tAuthor: "
+ Books.get(i).getAuthor() + "\n\t\tThis Books ID is: " + Books.get(i).getBookID() + "\t\t\t\t\t\t"
+ "\n\t\tIs this book on loan? " + Books.get(i).getOnLoan() + "\t\t\t\t\t"
+ "\n\t\tThe number of times which this book has been loaned: " + Books.get(i).getNumOfLoans()
+ "\t\t");
}
}
// method to remove permanently a book object
public void removeBook() // the parameter that is passed through
// is the book id of the book that is to
// be removed
{
Scanner input = new Scanner(System.in);
int bookID = 0;
boolean successful = false;
try {
do {
System.out.println("Please enter the book ID of the book you wish to delete");
bookID = input.nextInt();
for (int i = 0; i < Books.size(); i++) {
if (bookID == Books.get(i).getBookID())
{
System.out.println("The Book " + Books.get(i).getTitle() + " was removed");
Books.remove(i);
successful = true;
break;
}
}
if (!successful) {
System.out.println("Book ID " + bookID + " does not exist");
}
} while (successful == false);
} catch (Exception e) {
System.out.println("ERROR: Invalid input" + "\nYou have been returned to the main menu");
}
}
public void editBook() {
boolean successful = false;
try {
do {
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the book ID of the book who's details you wish to change");
int bookID = sc.nextInt();
sc.nextLine();
for (int i = 0; i < Books.size(); i++) {
if (Books.get(i).getBookID() == bookID) {
System.out.println("Please enter the new name of the book:");
String newTitle = sc.nextLine();
Books.get(i).setTitle(newTitle);
System.out.println("Please enter the name of the author of the book:");
String newAuthor = sc.nextLine();
Books.get(i).setAuthor(newAuthor);
System.out.println("Change of book details successful" + "\nNew book title: " + newTitle
+ "\nNew author: " + newAuthor);
successful = true;
}
}
if (!successful) {
System.out.println("This book does not exist ");
}
} while (successful == false);
} catch (Exception e) {
System.out.println("ERROR: Invalid input" + "\nYou have been returned to the main menu");
}
}
public void addBook() {
boolean successful = false;
int bookID = 0;
String title = "";
String author = "";
Scanner input = new Scanner(System.in);
do {
System.out.println("Please assign a 3 digit number for the books ID ");
bookID = input.nextInt();
input.nextLine();
if(bookID > 99 && bookID <1000){
for (int i = 0; i < Books.size(); i++) {
if(Books.get(i).getBookID()!= bookID){
successful = true;
} else {
System.out.println("This book ID already exists ");
}
}
} else { System.out.println("You must enter a number between 99 and 1000 ");
}
} while (successful == false);
do {
System.out.println("Please enter the name of book");
title = input.nextLine();
for (int i = 0; i < Books.size(); i++) {
if (Books.get(i).getTitle().equalsIgnoreCase(title)) {
System.out.println("ERROR: This book already exists");
successful = false;
} else {
successful = true;
}
}
} while (successful == false);
do {
System.out.println("Please enter the author of the book");
author = input.nextLine();
successful = true;
} while (successful == false);
Book Book = new Book(bookID, title, author, false, 0, 0);
Books.add(Book);
System.out.println(
"Book creation succcessful:" + "\nTitle: " + title + "\nAuthor: " + author + "\nBook ID:" + bookID);
}
public void loanBook() {
Scanner input = new Scanner(System.in);
boolean successful = false;
do {
System.out.println(
"\nPlease enter the book ID of the book that you wish to take out (Press 9 to exit to the main menu)");
int bookID = input.nextInt();
if (bookID == 9) {
successful = true;
break;
}
for (int i = 0; i < Books.size(); i++) {
if (Books.get(i).getBookID() == bookID) {
do {
System.out.println("\nHow long would you like to loan the book for (20 Days maximum):");
int durationOnLoan = input.nextInt();
if (durationOnLoan <= 20 && 1 <= durationOnLoan) {
Books.get(i).setDurationOnLoan(durationOnLoan);
successful = true;
} else {
System.out.println("The number of days you have entered is invalid");
}
} while (successful == false);
System.out.println("\nThe book " + Books.get(i).getTitle() + " is now on loan");
Books.get(i).setOnLoan(true);
Books.get(i).setNumOfLoan(Books.get(i).getNumOfLoans() + 1);
successful = true;
}
}
if (successful == false) {
System.out.println("This book does not exist ");
}
} while (successful == false);
}
public void returnBook() {
boolean successful = false;
Scanner input = new Scanner(System.in);
try {
do {
System.out.println(
"Please enter the book ID of the book you wish to return (Press 9 to exit to the main menu");
int bookID = input.nextInt();
input.nextLine();
if (bookID == 9) {
successful = true;
}
for (int i = 0; i < Books.size(); i++) {
if (Books.get(i).getBookID() == bookID) {
if (Books.get(i).getOnLoan() == true) {
System.out.println("How long did you loan the book for?");
int durationOnLoan = input.nextInt();
if (durationOnLoan > Books.get(i).getDurationOnLoan()) {
durationOnLoan -= Books.get(i).getDurationOnLoan();
if (durationOnLoan < 3) {
System.out.println("You are " + durationOnLoan
+ " day(s) late in returning the book" + "\nYou have been fined £3."
+ "\n The book " + Books.get(i).getTitle() + " is now returned");
successful = true;
} else {
System.out.println("You are " + durationOnLoan + " days late in returning the book"
+ "\nYou have been fined £6.");
System.out
.println("The book " + Books.get(i).getTitle() + " has now been returned");
successful = true;
}
} else {
Books.get(i).setOnLoan(false);
System.out.println("The book " + Books.get(i).getTitle() + " has now been returned");
successful = true;
}
} else if (Books.get(i).getOnLoan() == false) {
System.out.println("\nThis book was not on loan");
System.out.println("\nYou have been returned to the main menu");
successful = true;
}
} else if (successful == false) {
System.out.println("This book does not exist");
}
}
} while (successful == false);
} catch (Exception e) {
System.out.println("ERROR: Invalid input" + "\nYou have been returned to the main menu");
}
}
}
MemberList class
package assignment;
import java.util.Scanner;
import java.util.ArrayList;
public class MemberList {
private ArrayList<Member> Members;
public MemberList(ArrayList<Member> Members) {
this.Members = Members;
}
public void addNewMember() {
Scanner input = new Scanner(System.in);
boolean successful = false;
int memberID = 0;
String memberName = "";
int memberAge;
String address;
int contactNumber;
System.out.println("\t\tCreate new member");
do {
System.out.println("Please enter your full name:");
memberName = input.nextLine();
if (!input.hasNextInt()) {
successful =true;
} else {
input.next();
System.out.println("Your name cannot contain a number");
}
} while (successful == false);
do {
try{
input.nextLine();
System.out.println("please create your unique 2 digit member ID");
memberID = input.nextInt();
for (int i = 0; i < Members.size(); i++) {
if (Members.get(i).getMemberID() == memberID) {
System.out.println("This member ID is already in use");
successful =false;
}
if (memberID <= 9 || memberID > 99) {
System.out.println("PLease enter 2 digit ID (between 10 and 100) ");
}
if(Members.get(i).getMemberID() != memberID && memberID > 9 && memberID < 100) {
successful = true;
}
}
} catch(NumberFormatException e)
{
System.out.println("Invalid input");
}
} while (successful == false);
do{
System.out.println("Please enter your age: ");
memberAge = input.nextInt();
if(!input.hasNextInt())
{
System.out.println("Invalid input");
} else{successful =true;}
}while(successful == false);
do{
System.out.println("Please enter your adress");
address = input.nextLine();
successful =true;
}while(successful==false);
do {
System.out.println("please enter your contact number:");
contactNumber = input.nextInt();
if(!input.hasNextInt())
{
System.out.println("Invalid input");
} else{successful = true;}
}while(successful==false);
Member newMember = new Member(memberID,memberName,memberAge,0,0,address,contactNumber);
Members.add(newMember);
}
public void displayMembers()
{
System.out.println("\t\t\t-----The current members in the library are-----");
for (int i = 0; i < Members.size(); i++)
{
System.out.println("\n" + "\t\t" + Members.get(i).getMemberName() + "\t\t\t" + "\n\t\tMember ID: "
+ Members.get(i).getMemberID() + "\n\t\tAge: " + Members.get(i).getMemberAge() + "\t\t\t\t\t\t"
+ "\n\t\tAddress: " + Members.get(i).getAddress() + "\t\t\t\t\t"
+ "\n\t\tContact number: " + Members.get(i).getContactNumber()
+ "\t\t" + "\n\t\tNumber of books loaned: " + Members.get(i).getNumOfBooksLoaned()
+ "\t\t" + "\n\t\tNumber of Late Fees: " + Members.get(i).getPenalties());
}
}
}
LibraryTester Class
package assignment;
import java.util.Scanner;
import java.util.ArrayList;
public class LibraryTester {
public static void main(String[] args) {
String title = "";
String author = "";
int bookID = 0;
ArrayList<Member> List = new ArrayList<Member>();
MemberList memberlist = new MemberList(List){};
Member John = new Member(10,"John McLaughlin", 44, 5, 0,"75 B Loughbeg Road Toomebridge",123456789);
List.add(John);
Member Cathy = new Member(11,"Cathy McLaughlin", 43, 7, 0,"75 B Loughbeg Road Toomebridge",123456789);
List.add(Cathy);
ArrayList<Book> list = new ArrayList<Book>();
Library library = new Library(list, );
Book HarryPotter = new Book(100, "Harry Potter and The Philosopher's Stone", "J.K Rowling", false, 5, 0);
list.add(HarryPotter);
Book theOriginOfSpecies = new Book(101, "The Origin Of Species", "Charles Darwin", false, 3, 0);
list.add(theOriginOfSpecies);
Book LOTR = new Book(102, "The Lord of The Rings: The Fellowship of The Ring", "J.R.R Tolkien", false,7,0);
list.add(LOTR);
Scanner input = new Scanner(System.in);
boolean B = true;
while (B == true) {
System.out.println(" \nMenu ");
System.out.println("Press 1 to add a book");
System.out.println("Press 2 to edit a books details");
System.out.println("Press 3 to delete a book");
System.out.println("Press 4 to take out a book on loan");
System.out.println("Press 5 to return a book");
System.out.println("Press 6 to see all the books in the library");
System.out.println("Press 7 to become a member");
System.out.println("Press 8 to see the members of the library");
System.out.println("Press 9 to exit the program");
switch (input.nextInt()) {
case 1:
library.addBook();
B = true;
break;
case 2:
library.displayBooks();
library.editBook();
B = true;
break;
case 3:
library.displayBooks();
library.removeBook();
B = true;
break;
case 4:
library.displayBooks();
library.loanBook();
B = true;
break;
case 5:
library.displayBooks();
library.returnBook();
break;
case 6:
library.displayBooks();
B = true;
break;
case 7:
memberlist.addNewMember();
break;
case 8:
memberlist.displayMembers();
B = true;
break;
case 9:
System.out.println("Exiting .....");
System.exit(1);
break;
default:
System.out.println("You have not entered a valid option");
break;
}
}
}
}
The error occurs at the code
Library library = new Library(list , ) {
};
I'm not sure what to put after the comma, I've tried everything and nothing seems to work. Any thoughts?
EDIT
Edited Library class
package assignment;
import java.nio.channels.MembershipKey;
import java.util.ArrayList;
import java.util.Scanner;
import org.omg.Messaging.SyncScopeHelper;
public class Library {
// Declared an array list of type book
private ArrayList<Book> Books;
private ArrayList<Member> members;;
public Library(ArrayList<Book> Books, ArrayList<Member> member) {
this.Books = Books;
this.members=member;
};
Edited LibraryTester class
ArrayList<Member> List = new ArrayList<Member>();
MemberList memberList = new MemberList(List){};
ArrayList<Book> list = new ArrayList<Book>();
Library library = new Library(list, memberList ){};
The error says "The constructor Library(ArrayList, MemberList) is undefined" But i've changed the relevant things in the library class?
You need to pass an array of Book and, a Member :
public Library(ArrayList<Book> Books, Member member)
Since Library class is having the constructor
public Library(ArrayList<Book> Books, Member member){};
you can't just create a object as you are doing in LibraryTester class.
you need to pass the second parameter i.e, object of Member class.
Here you miss a member:
Library library = new Library(list, );
Try to add it like this creating an object of Member:
Member memberlist = new Member(10,"Joe Blogs", 44, 5, 0,"Bleaker Street",123456789);
Library library = new Library(list, memberlist);

is there any Exception in Java that to detect no input?

What Exception do I need to add to my try catch block if I want to detect if a user has entered any characters?
This is my code where I want to know if the user hasn't input anything or if the user's input was already saved in an addressbook. I am using an array to store my entries:
public void addEntry() {
entry[counter] = new AddressBookEntry();
entry[counter].setName(JOptionPane.showInputDialog("Enter name: "));
entry[counter].setAdd(JOptionPane.showInputDialog("Enter add: "));
entry[counter].setPhoneNo(JOptionPane.showInputDialog("Enter Phone No.: "));
entry[counter].setEmail(JOptionPane.showInputDialog("Enter E-mail: "));
counter++;
}
Do I need a try-catch or a condition? Here's my complete code:
public class AddressBook {
private AddressBookEntry entry[];
private int counter;
private String SName;
private int notfound = 0;
public static void main(String[] args) {
AddressBook a = new AddressBook();
a.entry = new AddressBookEntry[100];
int option = 0;
try {
while (option != 5) {
String content = "Choose an Option\n\n"
+ "[1] Add an Entry\n"
+ "[2] Delete an Entry\n"
+ "[3] Update an Entry\n"
+ "[4] View all Entries\n"
+ "[5] View Specific Entry\n"
+ "[6] Exit";
option = Integer.parseInt(JOptionPane.showInputDialog(content));
switch (option) {
case 1:
a.addEntry();
break;
case 2:
a.deleteEntry();
break;
case 3:
a.editEntry();
break;
case 4:
a.viewAll();
break;
case 5:
a.searchEntry();
break;
case 6:
System.exit(1);
break;
default:
JOptionPane.showMessageDialog(null, "Invalid Choice!");
}
}
}catch(NumberFormatException e){
JOptionPane.showMessageDialog(null, "Please Choose a Number in the displayed Menu");
}
}
public void addEntry() {
entry[counter] = new AddressBookEntry();
entry[counter].setName(JOptionPane.showInputDialog("Enter name: "));
entry[counter].setAdd(JOptionPane.showInputDialog("Enter add: "));
entry[counter].setPhoneNo(JOptionPane.showInputDialog("Enter Phone No.: "));
entry[counter].setEmail(JOptionPane.showInputDialog("Enter E-mail: "));
counter++;
}
public void viewAll() {
String addText = " NAME\tADDRESS\tPHONE NO.\tE-MAIL ADD\n\n";
int nonNull = 0;
for (int i = 0; i < entry.length; i++) {
if (entry[i] != null) {
addText = addText + entry[i].getInfo() + "\n";
nonNull++;
}
if (nonNull == counter) {
break;
}
}
JOptionPane.showMessageDialog(null, new JTextArea(addText));
}
public void searchEntry() {
SName = JOptionPane.showInputDialog("Enter Name to find: ");
searchMethod();
}
public void searchMethod() {
for (int i = 0; i < counter; i++) {
if (entry[i].getName().equals(SName)) {
JOptionPane.showMessageDialog(null, entry[i].getInfo2());
notfound = 0;
break;
} else {
notfound++;
}
}
if (notfound != 0) {
JOptionPane.showMessageDialog(null, "Name Not Found!");
}
}
public void editEntry() {
SName = JOptionPane.showInputDialog("Enter Name to edit: ");
for (int i = 0; i < counter; i++) {
if (entry[i].getName().equals(SName)) {
entry[i] = new AddressBookEntry();
entry[i].setName(JOptionPane.showInputDialog("Enter new name: "));
entry[i].setAdd(JOptionPane.showInputDialog("Enter new add: "));
entry[i].setPhoneNo(JOptionPane.showInputDialog("Enter new Phone No.: "));
entry[i].setEmail(JOptionPane.showInputDialog("Enter new E-mail: "));
notfound = 0;
break;
} else {
notfound++;
}
}
if (notfound != 0) {
JOptionPane.showMessageDialog(null, "Name Not Found!");
}
}
public void deleteEntry() {
SName = JOptionPane.showInputDialog("Enter Name to delete: ");
for (int i = 0; i < counter; i++) {
if (entry[i].getName().equals(SName)) {
JOptionPane.showMessageDialog(null, "Found!");
entry[i] = null;
break;
}
}
}
}
I am having problem with my addEntry() method, because I want to detect if the user's new added entry was already stored in my addressbook and if the user doesn't typed anything when I ask "Enter Name:" in JOptionPane and still press OK.
Although not much clear about your question, I will try to answer it.
In this case, you can manually create your own exception here like,
throw new MyException();
Since your condition "The user didn't enter any character" is itself not clearer, I would suggest that you can try throwing exception by checking the no of arguments passed on the command-line.
If it's 0 i.e no arguments are passed, you can throw your own exception.
But by itself, no exception will be thrown.
I don't know of any exception, but you can use the length method.
Example:
input=(JOptionPane.showInputDialog(frame1, "what do you want?"));
if(input.length() > 0) {
l1.setText("a " + input + " on the way!");
}
else{
l1.setText("would you please choose something");
}
if length is greater then zero
From your updated question, it appears as if you are talking about user input from dialog boxes. The javadoc says that the showInputDialog methods return either the user's String (which could be empty) or null if the user canceled the dialog.
No exception is thrown. The user canceling the dialog is not "exceptional".
In general, when some method throws an exception and you don't catch it, either the compiler alerts you about this (for checked exceptions) or when the exceptions is thrown on runtime, you see a nice stack trace on the console (standard error). If you don't see this, then either you have caught (and thrown away) this exception, or there is no exception.
The user didn't enter any character by itself is not a condition which causes anyone to throw an exception, we would need more context.

problem with comparing a name from getter method to user input string

i'm having trouble comparing in my if statement, in C programming i am using "==" double equal sign to compare two string...
how about comparing a string using getter method to a new string... i try to use the double equal sign but i was prompted to change it into this:
if (entry[i].getName().equals(EName))
by the way this is my whole code:
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
public class AddressBook {
private AddressBookEntry entry[];
private int counter;
private String EName;
public static void main(String[] args) {
AddressBook a = new AddressBook();
a.entry = new AddressBookEntry[100];
int option = 0;
while (option != 5) {
String content = "Choose an Option\n\n"
+ "[1] Add an Entry\n"
+ "[2] Delete an Entry\n"
+ "[3] Update an Entry\n"
+ "[4] View all Entries\n"
+ "[5] View Specific Entry\n"
+ "[6] Exit";
option = Integer.parseInt(JOptionPane.showInputDialog(content));
switch (option) {
case 1:
a.addEntry();
break;
case 2:
break;
case 3:
a.editMenu();
break;
case 4:
a.viewAll();
break;
case 5:
break;
case 6:
System.exit(1);
break;
default:
JOptionPane.showMessageDialog(null, "Invalid Choice!");
}
}
}
public void addEntry() {
entry[counter] = new AddressBookEntry();
entry[counter].setName(JOptionPane.showInputDialog("Enter name: "));
entry[counter].setAdd(JOptionPane.showInputDialog("Enter add: "));
entry[counter].setPhoneNo(JOptionPane.showInputDialog("Enter Phone No.: "));
entry[counter].setEmail(JOptionPane.showInputDialog("Enter E-mail: "));
counter++;
}
public void viewAll() {
String addText= "";
for (int i = 0; i < counter; i++) {
addText = addText+(i+1)+ entry[i].getInfo()+ "\n";
}
JOptionPane.showMessageDialog(null, new JTextArea(addText));
}
public void editMenu() {
int option = 0;
while (option != 6) {
String content = "Choose an Option\n\n"
+ "[1] Edit Name\n"
+ "[2] Edit Address\n"
+ "[3] Edit Phone No.\n"
+ "[4] Edit E-mail address\n"
+ "[5] Back to Main Menu";
option = Integer.parseInt(JOptionPane.showInputDialog(content));
switch (option) {
case 1:
editName();
break;
case 2:
editAdd();
break;
case 3:
editPhoneNo();
break;
case 4:
editEmail();
break;
case 5:
return;
default:
JOptionPane.showMessageDialog(null, "Invalid Choice!");
}
}
}
public void editName() {
EName = JOptionPane.showInputDialog("Enter name to edit: ");
for (int i = 0; i < counter; i++) {
if (entry[i].getName().equals(EName)) {
//JOptionPane.showMessageDialog(null, "found");
entry[i].setName(JOptionPane.showInputDialog("Enter new name: "));
}else {
JOptionPane.showMessageDialog(null, "Entered Name not Found!");
}
}
}
public void editAdd() {
EName = JOptionPane.showInputDialog("Enter name to edit: ");
for (int i = 0; i < counter; i++) {
if (entry[i].getName().equals(EName)) {
//JOptionPane.showMessageDialog(null, "found");
entry[i].setAdd(JOptionPane.showInputDialog("Enter new Address: "));
}else {
JOptionPane.showMessageDialog(null, "Entered Name not Found!");
}
}
}
public void editPhoneNo() {
EName = JOptionPane.showInputDialog("Enter name to edit: ");
for (int i = 0; i < counter; i++) {
if (entry[i].getName().equals(EName)) {
//JOptionPane.showMessageDialog(null, "found");
entry[i].setPhoneNo(JOptionPane.showInputDialog("Enter new Phone No.: "));
}else {
JOptionPane.showMessageDialog(null, "Entered Name not Found!");
}
}
}
public void editEmail() {
EName = JOptionPane.showInputDialog("Enter name to edit: ");
for (int i = 0; i < counter; i++) {
if (entry[i].getName().equals(EName)) {
//JOptionPane.showMessageDialog(null, "found");
entry[i].setEmail(JOptionPane.showInputDialog("Enter new E-mail add: "));
}else {
JOptionPane.showMessageDialog(null, "Entered Name not Found!");
}
}
}
}
and this is my other class:
public class AddressBookEntry {
private String name;
private String add;
private String phoneNo;
private String email;
private int entry;
public String getAdd() {
return add;
}
public String getEmail() {
return email;
}
public int getEntry() {
return entry;
}
public String getName() {
return name;
}
public String getPhoneNo() {
return phoneNo;
}
public void setAdd(String add) {
this.add = add;
}
public void setEmail(String email) {
this.email = email;
}
public void setEntry(int entry) {
this.entry = entry;
}
public void setName(String name) {
this.name = name;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public String getInfo() {
String Info = "NAME\tADDRESS\tPHONE NO.\tE-MAIL ADD\n"
+ name + "\t " + add + "\t " + phoneNo + "\t " + email + "\n";
return Info;
}
public String getInfo2() {
String content = "INFORMATION:\n\n"
+ "Name: " + name + "\n"
+ "Address: " + add + "\n"
+ "Tel. No: " + phoneNo + "\n"
+ "Email Add: " + email + "\n\n";
return content;
}
}
PLEASE PARDON MY CODE... i am new at java.... please help....
what i want to is traverse to all the array and edit the specific detail if the user input was equals to the entry[i].getName()
thanks a lot in advance...
Use equals() if you want to compare the representation of the string and not its object identity.
Assume we have: String s = "hello";
s == s
=> true // they are the *same* object
"hello" == new String("hello") // see comment below...
=> false // they are different objects representing the same string of text
"hello".equals("hello")
=> true
s.equals("hello")
=> true
There are at least 3 things to understand:
Java: == tests whether two references point to the same object, whereas equals tests whether two objects have the same content. So, even if two Strings have the same content, == may give false whereas s1.equals(s2) will give true. You can find loads about this on google.
C: In C, you shouldn't compare two strings using == either. Strings in C generally are char* (or const char*), and you should compare them with strcmp (or else you will run into the same problems as in Java).
C++: instances of std::string can be compared using ==.

Categories

Resources