Implementing PhoneDirectory Using Simple Array Of DirectoryEntry Objects

Apr 24, 2014

Having supplied an interface the question arises as to how it should be implemented. There are a number of possibilities including the use of an array list or a linked list; however it is perfectly possible, and in fact instructive, to begin by implementing PhoneDirectory using a simple array of DirectoryEntry objects. This approach is illustrated below:

public class ArrayPhoneDirectory implements PhoneDirectory
{
private static final int INIT_CAPACITY = 100;
private int capacity = INIT_CAPACITY;  
// holds telno of directory entries
private int size = 0;
// Array to contain directory entries
 
[Code] ......

Develop a tester class called ArrayPhoneDirectoryTester . As usual all methods in the class being tested should be executed at least once by the test driver. Supply standard test documentation - Test Plan, Test Data and Test Log.

In addition to the methods described in the interface the class ArrayPhoneDirectory contains three private methods listed below:

// Searches the array of directory entries for a specific name
private int find(String name){}
 
// Adds a new entry with the given name and telno to the array of
// directory entries
private void add(String name, String telno){}
 
// Creates a new array of directory entries with twice the capacity
// of the previous one
private void reallocate(){}

These methods can be thought of as "helper" methods in that they assist the work of the public methods of the class. For example, the find() method is used by the lookUpEntry() method to locate the position of the a specific directory entry.

Pseudo-code algorithms for the methods of ArrayPhoneDirectory are listed below

Algorithm for load

create a Scanner to read file
while (not end of file)
use Scanner to read the name
use Scanner to read the telno
create a DirectoryEntry
add the new entry to theDirectory
close file

This method is a good place to start coding but note that load makes use of the add method in case the number of entries stored in the text file has exceeded the initial capacity of the directory. So to implement load fully you will need a working version of the "helper" method add. However you can do this in stages by first developing a basic version of add which does not increase the size of the directory. In reading data from the file you may assume that the file only contains matched pairs of names and numbers. There is no need to consider the case of a name not being associated with a telephone number.

Algorithm for addChangeEntry
call find to see whether name is in directory
if name is in theDirectory
change the telno using setNumber
return the old telno
else
add a new entry to theDirectory using method add
return null

[Code] ....

I don't know how to do any of this at all

View Replies


ADVERTISEMENT

Java Servlet :: Implementing JPA Hibernate Simple Application Using One To Many Relationship

May 8, 2012

I am implementing JPA hibernate simple application using one to many relationship.

Relation ship is Comapny (1)----------- Department(*)

Company.java is as follow :

package com.web.pojo;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;

[Code] .....     

What I am doing is , I am adding new department to existing company. After execution above code

Table created are :

1. Company table with id and name
2. Department table with deptId , deptName , compId.

so at the time adding department , it does not threw any exception but updates records in department as

1(Id),Development(DeptName),null(compId) .

I am not getting why it is not updating compId column.

View Replies View Related

Implementing Deserialization Of Objects?

Jul 16, 2014

Say you have a bunch of animals, `Rat` `Cat` `Dog` and `Fish`, and you want to serialize/deserialize these animals. Each has its own `serialize()` method. That all works fine and good, if you want to save your Cat to a file, you call `Cat.serialize()` and then you write it to a file.

But what about deserializing? Sure, you could save an extra bit of data that states the type of animal, then use reflection to get a static method (say, `deserialize(String serialized)`) and then invoke it. But that's not safe. What if someone creates a new animal 'Rabbit' and doesn't include a `deserialize(String serialized)` method? Sure, you could then just catch the error and ignore the issue, but that seems unclean and bad practice.

You could also create an enum. Each item in the enum must have a `deserialize(String serialized)` method, and the aforementioned piece of data that states the type references the name of its enum item. Problem is, not very adaptable. Enums don't allow for other animals to be added at runtime.

The way I have been solving this issue is mapping the name of the objects against a deserializer object. Basically each animal would have to 'register' itself by entering it's name and deserializer (implements `Deserializer` interface) object into a HashMap. The deserializer object can then be retrieved via the name of the animal at a later time.

My question is, what is the best method to go about implementing deserialization? Also, is the method I have been using good/bad practice?

Finally, if you are wondering why animals would be added at runtime, the reason is because animals might be added by other non accessible parts of the program, or by things such as plugins.

Example of the method I have been using is below.

Animal Interface

Java Code:

public class Animal{
public String serialize();
} mh_sh_highlight_all('java'); Deserializer Interface

[code]....

And when you needed to deserialize:

Java Code:

Deserializer d=AnimalSpecies.getSpeciesDeserializer(serialized.split(AnimalSpecies.DELIMITER)[0]);
if (d!=null){
d.deserialize(serialized);
} mh_sh_highlight_all('java');

What I mean by this is that any serialized Animal must have a way of identifying which animal it is so that it's deserializer can be accessed. This can be worked around by implementing a wrapper that adds this information directly before it is written to a file, and removes it directly before deserialization.

Why not use built in serialization/deserialization? I would like the serialized data to be readable and easily editable.

View Replies View Related

Simple Cannon Game - How To Delete Objects

Oct 22, 2014

I am using libgdx and box2d to try to make a simple cannon game.

When I have the cannonball collide with another object I want to delete that object and have it stop calling all of it's functions. It doesn't seem like I can have it delete itself, and the contactListener has a reference to the cannonball and other object, but if I set either to null, it seems the original reference still exists and the object isn't deleted.

View Replies View Related

Implementing Two Stack In One Array?

Jan 5, 2015

is this program correct? for Implementing two Stack in one array. how can i solve it ?

public class Stackation11 {
int max = 10;
int [] array = new int[max];
int top;
int top1;
Stackation11(){

[code]....

View Replies View Related

Implementing Merge Sort On Given Array

Jun 15, 2014

Merge sort implementation on the given array i listed in the code below. I know Arrays.sort() or Collections.sort() could do the trick but i want to achieve it through merge sort.

import java.util.*;
public class Merge{
public static void main(String[] args){
String[] myStringArray=new String[]{"z","a","z","b","c","e","z","f"
,"g","a","w","d","m" ,"x","a","R"
,"q","r","y","w","j","a","v","z","b"};
}
}

View Replies View Related

Simple Function That Returns Array

Jun 1, 2014

Basically, it's to write a method that takes in, and then returns another array, whose first element is the average of the first two numbers, last element is the average of the last two, and then everything else is just the average of that index, the one before, and the one after. {1, 2, 4, 8} would return {1.5, 2.33333, 4.66666, 6}.I'm currently getting everything fine, except am not getting the last number (i.e. '6').

public class Arrays {
public static void main(String [] args){
double [] a1 = {1, 2, 4, 8};
for (int i = 0; i < a1.length; i++)
System.out.println(a1[i]);

[code]....

View Replies View Related

Finding Simple Moving Average With Array

Apr 8, 2014

How can I find out the simple moving average by just using the numbers stored in an array?

View Replies View Related

How To Prevent A User From Going Out Of Bounds In Simple Array Game

Apr 26, 2015

I am making a very simple 2D array game where the player is asked what size they would like the game board to be. After entering, it displays the board and the player 'P' starts at index [0][0]. After that, they are asked for an action, which can be "up", "down", "left", "right", or "exit". I will be including some extra later (like a treasure at the end, or random obstacles), but for now this is what the game consists of.

I was instructed to "do nothing" when/if the player attempts to go out of bounds. I am trying to simply print an error, such as "Out of bounds! Try again.", then prompt the player again for an action. I even tried to make a boolean method to catch it, but to no avail.

I don't want the exception to occur at all. I just simply want the error message to print to the player and ask for another action. I would prefer not to use try/catch, or try/catch/finally since I already tried that and it still gave the exception error.This program consists of two classes. I will show the class containing the main first, then the client-server type class second.

import java.util.Scanner;
public class Driver {
public static void main(String[] args) {
World world = new World();
boolean keepPlaying;
keepPlaying = true;
boolean isOutOfBounds;
isOutOfBounds = false;
int height = 0;
int width = 0;
int x = 0;
int y = 0;

[code]....

View Replies View Related

Array Of Objects

Mar 28, 2014

Exercise the Coin class using a driver class in which 5 coins are flipped, as a group, 1024 times. Display the number of times exactly 4 tails are obtained. Display the number of times exactly 5 tails are obtained. Use an array of Coin.

how to put an object into an array?I know how to make a coin class with a Heads and Tails, but I dont know how to make 5 coins all at once.

View Replies View Related

Syntax For Array Of Objects

Apr 10, 2014

I know the first line below creates an object but the second line creates an array of cars, I'm just not sure how it does that. I can see sportsCar is one object in the array but the others are written in a different way. It seems there should a couple names there instead. Please explain the syntax in this code that's highlighted. I don't know how to make sense of it and I've read through the book where I got it where it explained creating objects.

Auto sportsCar = new Auto("Ferrari", 0, 0.0);
Auto [] cars = {new auto("BMW", 100, 15.0), sportsCar, new Auto()};

View Replies View Related

JSF :: Submit Array Of Objects?

Apr 24, 2014

I have a list of objects in my bean (ex: List<Apple> applies = new ArrayList<Apple>() ).The object has several fields (ex: supplier, color, width, height, breadth, etc.)I want to show this list on the front end. However I also want to allow the user to edit the attributes of the apples.So from the front end I will have like a list of fields where a set of fields is related to a single object in the list.I would also like to add/delete apples.

What first came to my mind is to map every field in the object Apple to a List. For example if Apple has field suppliers and field color then in the bean I would create two Lists, List<String> supplier, and List<String> color.From the front end I would display the contents of these Lists rather then the List<Apple> apples.T

he name of the field would be the same for each set of attributes.On save (form submit) the Lists would be re-populated with the field values (changed or not) and then I would be my Apple objects from the bean before saving in database.However I am not sure if there is something in JSF that can achieve this in a simple way, working only with List<Apple> rather than adding additional Lists.

View Replies View Related

Array Holding Many Objects

Jun 29, 2014

okay,I created a program that demonstrated an array holding a number of objects, each from different classes.the printout I got for the first program ended up being gibberish. when I made the program a second time, I got the correct result.I've been trying to pinpoint the anomaly but I can't seem to find it. So ill try breaking down what I did?

Goal:The purpose of the program was to have a single Class (we'll call the Class 'Animal') to pass the parameters of a previously made method. This method would, amongst other things, call on an array.Further, I would then make subclasses of the Class Animal, and then use them as well to pass the method parameters, thus demonstrating subclasses can be used in place of the super class.

3 of these classes were made purely to as a "place setter". the Classes called "Cat" and "Dog" respectively were created to be subclasses of the Class Animal (with no other code inside them aside from "extends Animal)the 3rd "place setter" called "ClasstoHoldObjects" was created to be the array class (ClasstoHoldObjects itself has no code in it aside from the class name)these are the ones we want.Animal class (which holds the coding meant to be used).Here is the Animal Class

public class Animal {
private ClasstoHoldObjects[] thelist = new ClasstoHoldObjects[5];
int i = 0;
public void add(ClasstoHoldObjects x){
if(i < thelist.length){

[code]....

the print out was this next, im putting THIS line in the array... june_6.Dog@a0dcd9 (and the same by the Cat object).I recognize june6 as the package name.

finally, I erased extra lines as well as comments and simplified class names to make the code more readable. If you want the original, or some class names are a bit off- I could give you the original with all its comments and longer named classes

View Replies View Related

Array With Objects And Polymorphism

Sep 18, 2014

I have a program I want to make (text based, no gui). There is the main class, an Employee class (sort of a template), a CrewMember class, and a Manager class.

I'll put the code for each class an explain the problem I have.

package polymorphism;
import java.util.Random;
public class Start {
public static void main(String[] args) {
Random rand = new Random();
Employee staff[] = new Employee[5];
for(int i = 0; i < staff.length; i++){

[Code] ....

Some of the code is a bit incomplete simply because I ran into the problem. As you can see I made an array in the Start class and it holds objects of Employee type, but create a new instance of either a crew member or a manager, sets their wages, hours, and bonus if applicable. I know if I create an array of a certain type, I can't call upon the subclass' method (Manager in this case) because it has a new method that I added. What I'm trying to do is pretty much call upon the getSalary() method in the Manager class/object, but of course I can't. What way would i be able to do that? I tried looking for some answers. I read about making the superclass abstract and implementing it into the subclasses. Would that be an option?

View Replies View Related

Sorting Array Of Objects With Strings?

Feb 14, 2015

An array has objects with String firstName, String lastName, int ID, char examType('M' or 'F'), and int score. Every object has both Midterm('M') and Final('F'). The array has to be sorted by the first Midterm- 'M' and immediately followed by the Final ('F') of the same person (object). Im having troubles with coming up with a proper algorithm with gettin the Final- 'F' after Midterm for the same person.

Java Code: public static Exam[] collateExams(Exam[] exams) {
Exam [] r = new Exam[10];
r = exams;
int[] position = new int[10];
int index = 0;
for(int i = 0; i < exams.length; i++)

[Code]...

View Replies View Related

Loading Interface Array Of Objects?

Oct 27, 2014

I have an assignment where I need to add an interface to an already-created program. I have an array of objects, where each object has a name, price, and priority.

In my original program (which worked), I had all of the objects in 1 class. The professor said that I should split up the name/price/priority into 3 different classes. So what I have is an array that belongs to an interface, and name/price/priority implements. But I am having trouble loading the data into the array (from another class) once I am done with loading name.

Here is what I have so far.

public class Main {
public static void main (String[] args){
Interface[] arr = new Interface[7];
Scanner keyboard = new Scanner(System.in);
System.out.println

[code]....

Line 18 in the ItemName class is giving me an error, and I know it is because arr is of type Interface, and I am trying to assign is a String. But I don't know how to do this. In my original program I was able to do arr[x].getName(); but when I do that in Main, I get errors.

how to assign to an interface array from multiple classes.

View Replies View Related

Searching Array Of Objects In Java

Jul 23, 2014

'm working on a program that is to act as an inventory for a book store. There are two classes (Store and Book), and numerous methods which you will see in my code. The program is supposed to read in an inventory from a file which contains 10 books (each row in the file represents a book with an ISBN number, the price of the book, and the number in stock)and store this file into an array of type Book[]. There is then to be another method to process a purchase interactively. The Store class is also to keep a count of how many books were sold at the time of closing and also how much was made that day.

I'm having some difficulty figuring out how I should set up the purchase processing method though. I've written out how I think it would be set up (not too familiar with the terminology, but I think it would be called pseudo code?) I'll include that now along with a few other notes.

public Book[] purchase(String isbn, double price, int copies) {
int itemsSold;
double totalMade;
Scanner input = new Scanner(System.in);
System.out.println("Please enter the ISBN number of the book you would like to purchase: ");

[Code] ....

So basically here's what needs to be accomplished with this portion of code:

1.Ask the user to enter the ISBN number of the book they'd like to purchase.
2.Search the array for the object that contains that ISBN.
3.If the ISBN isn't found in the array, display a message stating that we don't have that book.
4.If the ISBN is found but the number of copies is 0, display a message saying the book is out of stock.
5.If the ISBN is found and the number of copies is greater than 0, ask the user how many copies they'd like to purchase.
6.If the number they enter is greater than the number of copies of that book in the array, display a message stating that and ask them to enter another quantity.
7.Once the purchase is complete I need to update the array by subtracting the number of copies of that particular book that was purchased.
8.Print the updated array.
9.Display a count of how many books were purchased, and how much money was made from the purchase.

I know that code has a lot of holes in it, but I'm just trying to get everything together and figure out how to do each step.

The part I'm stuck on right now is trying to figure out how to search the array to first see if the ISBN that was entered is in the array, and then to find the number of copies of the book with that ISBN number.

In case it will visualize what this array looks like, here's a print out of the array from a sample run I just did.

ISBN: 1234567, Price: 31.670000, Copies: 0
ISBN: 1234444, Price: 98.500000, Copies: 4
ISBN: 1235555, Price: 27.890000, Copies: 2
ISBN: 1235566, Price: 102.390000, Copies: 6

[Code] ....

View Replies View Related

Dynamic Initialization Of 2D Array Of Objects?

Aug 15, 2014

if, instead of an ArrayList, can I do the following to initialize a Dyanmic array ? :

First, in my class, I have :

class Example{
private int rows;
private int columns;
private AnotherClass[][] 2DArray;
public Example(int rows, int columns){
this.rows = rows;
this.columns = columns;

[code]....

View Replies View Related

How To Access Data In Array Of Objects

Apr 23, 2014

I want to keep count of how many students are in my array. the array i made up of objects from other classes. like the class Student how do i do this. i have tried contains but better way it to to a loop to go through the array and determine if each object is a particular type but i don't know how to do this. here is the code

import java.util.*;
import java.util.ArrayList;
public class Driver {
public static void main(String[] args){
/* Comments required
PersonFileReader pfr = new PersonFileReader("person.dat");
ArrayList<Person> testData = pfr.readData();
Database db = new Database(testData);

[Code] .....

View Replies View Related

Creating Array Of Objects In Constructor

Mar 16, 2014

I want to create a simple app that takes a name from the console then compares the name to a small phone book,when the name matches another name it will return the associated phone number.

I have a small contacts class which has name and number fields,Then I have a phone book class which populates an array with 4 contact objects that I can compare the entered number against.

here is my contacts class

public class Contact
{
String name;
int number;

[Code].....

In the main method I am just trying to print out one of the fields for one contact to see if I can actually access it to compare it to the name entered.Its saying "MaryJones" cannot be resolved to a type.I'm guessing I cant create all that code in the constructor?

View Replies View Related

Adding New Object To The End Of Array Of Objects

Feb 8, 2015

I am trying to build a method that takes an array of object and adds a new object of that type to the end of it . ONLY ALLOWED TO USE ARRAY , NO ARRAYLISTS VECTORS ECT . i realize that if the array is full you can use the java copy array method to make a new array and double its size until a certain point . The MAX AMOUNT OF OBJECTS is a constant that is 100 but for some reason even when executing my code i keep getting null pointer exceptions or index out of bounds errors , i have written this method many times now with out any success.

My question is how do I write a method that adds an object to the end of an array and if there are no spots left copies the current array into a new array and extend the size

private Animal [] objects;
final int MAX_ANIMALS = 100;
public AnimalObject()
{
objects = new AnimalObject[MAX_ANIMALS];
}
public AnimalObject(Animal[]a)

[Code] ....

View Replies View Related

Adding Points Objects Into Array

Oct 24, 2014

I am trying to add Point objects into an Array.This is my code to read in data

Java Code:

public void readRoadMap(File road) {
try{
String line;
BufferedReader br = new BufferedReader(new FileReader(road));
while((line = br.readLine()) !=null){
this.points.add(new Point(line));

[code]....

View Replies View Related

Create A Static Array Of Objects In Java?

Jan 2, 2014

Im looking for a means to store groups of static data..

so I understand these simple string arrays...

Java Code:

private static String[] names = new String[] {
"aidanmack",
"johnsmith"
}
private static String[] ages = new String[] {
"30",
"30"
} mh_sh_highlight_all('java');

But can I not combine that into an array of objects? something along the lines of what you would do with json? like...

Java Code:

private static array[] multi = new array(){
{"name":"AIDANMACK","age":"30"},
{"name":"johnsmith","age":"31"}
} mh_sh_highlight_all('java');

View Replies View Related

How To Give Values To Array Objects Without Using Loop

Apr 3, 2014

The main method should creates a Student object with name as "Bill" and marks as {88,92,76,81,83} and print it.

Java Code:

class TestStudent {
public static void main(String args[]) {
Student1 st = new Student1();
st.name = "bill";
Student st1[] = new Student[6];
//This gives error
st1[].marks = {1, 5, 8, 9, 7, 6}; mh_sh_highlight_all('java');

View Replies View Related

Involving Array Of Objects And Referencing Methods Of Each

Nov 26, 2014

I'm working on a project that involves the following:

-Creating a superclass of bankaccounts
-Creating two subclasses, checkingaccount and savingaccount
-Each of the two subclasses has different methods (writeCheck for checking, for example)
-Both types are created in a main class bank and stored in the same array

So let's say a user goes through the menus and creates a few savingAccounts and a few checkingAccounts (stored in the accounts[] array). Then, to write a check from one account, the user can enter the account number (a string), and the method will use a for loop to cycle through the array until it hits an account number match. Then it checks that it's the correct account type and calls methods from the subclass.

Problem here is that some methods work and some don't. In the following example:

for (BankAccount account: accounts) {
if (account.getAccountType().equals("Checking")) {
do {
if (account.getAccountNumber().equals(accountNumber)) {
amount = Double.parseDouble(JOptionPane.showInputDialog(

[Code] .....

The getAccountNumber method works but writeCheck is throwing an error. I tried creating a method in the superclass and overriding it in the subclasses but with no success.

View Replies View Related

Dynamically Add Objects To Array In Any Position In Java

Feb 6, 2015

I have an assignment in which I have to design a method where I add an object at any given position in an array and shift the elements already in the array to make room. For example I have a collection class which holds trading card objects. So I wish to add a new trading card to this collection at a specified index or position with out deleting the current object already stored in the array . All this has to be done without the use of array lists, vectors or any abstract data types besides arrays . My question is how do I accomplish this . Say I wish to add a new trading card in position 4 the new card is added to my array and the card currently in position 4 gets moved to position 5 and the card in position 5 gets moved to 6 etc. The maximum amount of cards my collection can hold is 100. How would I add my trading card object to the specified position without overwriting what is currently there and shifting all other elements?Here is my current code.

public class CardCollection {
public BaseballCard [] collection;
final int MAX_CARDS = 100;
public CardCollection() {
collection = new BaseballCard[MAX_CARDS];
}
public CardCollection(BaseballCard[]c)

[code]...

position refers to the position in the CardCollection and not the position inside the array.

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved