Why is this an unreachable statement? Java - java

The unreachable statement is: thisCustomer = findCustomer(theCustomerID);. I cannot figure out why. thisCustomer is an attribute of Customer object, findCustomer() is a method listed below, and theCustomerID is the parameter of the method this statement is in. The problem is in rentOutApt(int theAptID, int theCustomerID, int theMonthsToRent) //3. This code is toward the bottom.
import java.util.ArrayList;
import java.util.Iterator; // If you choose to use one.
/**
* .AptRentalAgency.
* Controller class.
*
* Name:
* Comment:
*
* For Dr. Nikhil Srinivasan's MIST 4600 Exam02 on 20140321.
*
* #author Dr. Nikhil Srinivasan
* #version 20140317
*
*/
public class AptRentalAgency
{
// instance variables
private int currentDate;
// These match the Customer objects:
private int customerID;
private String customerName;
private double customerBalance;
private int customerAptID; // 0 if he or she does not currently have a apartment.
private int customerCreditRating;
// These match the Apartment objects:
private int aptID;
private String aptName;
private String aptAddress;
private int aptSize;
private double aptRent;
// ****** The following are set when the apt is rented:
private int aptCustomerID; // 0 if not rented.
private double aptDeposit; // 0 if not rented
private int aptMonthsRented; // 0 if not rented.
private int aptRentalDate; // 0 if not rented.
// There are a number of important nonfields that are to be computed
// in their accessor (get) methods as needed:
private double aptDepositMultiplier;
private double aptTotalCost;
// These are for the current Customer and current Apt objects:
Customer thisCustomer;
Apartment thisApt;
// These are the needed ArrayLists:
ArrayList<Customer> customers;
ArrayList<Apartment> apts;
// ReadFile objects:
private ReadFile aptReader; // Declare a ReadFile object to read from the AptData.txt file.
private ReadFile customerReader; // Declare a ReadFile object to read from the customerData.txt file.
/**
* AptRentalAgency Constructor
*/
public AptRentalAgency()
{
// Set the currentDate:
currentDate = 20140321;
// Create the ArrayLists:
customers = new ArrayList<Customer>();
apts = new ArrayList<Apartment>();
// Read in the Apt objects and Customer objects. Load them into the ArrayLists.
readApts();
readCustomers();
}
/**
* .readApts.
* Reads in the Apt objects.
*/
private void readApts()
{
aptReader = new ReadFile("AptData.txt");
aptReader.setSeparator(",");
// Read and Load the Data:
for(aptReader.readInputLine(); !aptReader.eof(); aptReader.readInputLine())
{
// Load the data into fields
aptID = aptReader.getIntField(1);
aptName = aptReader.getStringField(2);
aptAddress = aptReader.getStringField(3);
aptSize = aptReader.getIntField(4);
aptRent = aptReader.getDoubleField(5);
aptCustomerID = aptReader.getIntField(6);
aptDeposit = aptReader.getDoubleField(7);
aptMonthsRented = aptReader.getIntField(8);
aptRentalDate = aptReader.getIntField(9);
// Construct thisApt
thisApt = new Apartment(aptID, aptName, aptAddress, aptSize, aptRent,
aptCustomerID, aptDeposit, aptMonthsRented, aptRentalDate);
// Add thisApt to the apts ArrayList.
apts.add(thisApt);
}
// End of Loop
System.out.println("\nAll apts read from the file and added to the ArrayList.\n");
}
/**
* .readCustomers.
* Reads in the Customer objects.
*/
private void readCustomers()
{
customerReader = new ReadFile("CustomerData.txt");
customerReader.setSeparator(",");
// Read and Load the Data:
for(customerReader.readInputLine(); !customerReader.eof(); customerReader.readInputLine())
{
// Load the data into fields
customerID = customerReader.getIntField(1);
customerName = customerReader.getStringField(2);
customerBalance = customerReader.getDoubleField(3);
customerAptID = customerReader.getIntField(4);
customerCreditRating = customerReader.getIntField(5);
// Construct thisCustomer
thisCustomer = new Customer(customerID, customerName, customerBalance, customerAptID, customerCreditRating);
// Add thisCustomer to the customers ArrayList.
customers.add(thisCustomer);
}
// End of Loop
System.out.println("\nAll customers read from the file and added to the ArrayList.\n");
}
/**
* .printAllCustomers.
*/
public void printAllCustomers()
{
// Print a header, then the list.
System.out.println("\nCurrent Customer List on " + currentDate + "\n");
System.out.println("CustID Name Balance Apt ID CreditRating");
System.out.println("------ ----------------- ------- ------- ------------");
for(Customer theCustomer: customers)
{
theCustomer.printInfo();
}
System.out.println("\nEnd of Customer List. \n");
}
/**
* .printAllApts.
*/
public void printAllApts()
{
// Print a header, then the list.
System.out.println("\nCurrent Apt List on " + currentDate + "\n");
System.out.println("AptID Apt Name Address Size Rent RenterID Deposit MonthsRented RentalDate");
System.out.println("----- ------------------- -------------------------- ---- ------- -------- ------- ------------ ----------");
for(Apartment theApt: apts)
{
theApt.printInfo();
}
System.out.println("\nEnd of Apt List. \n");
}
// ****************** Do your work after this point ********************************
/**
* .find a customer.
*/
public Customer findCustomer(int theCustomerID)
{
for(Customer theCustomer: customers)
{
if (theCustomer.getCustomerID() == theCustomerID)
{
return theCustomer;
}
}
return null;
}
/**
* .find Apartment.
*/
public Apartment findApartment(int theAptID)
{
for(Apartment theApt: apts)
{
if (theApt.getAptID() == theAptID)
{
return theApt;
}
}
return null;
}
/**
* .customerAddMoney.
* Part a
*/
public void customerAddMoney(int theCustomerID, double theAmountToAdd)
{
// Find the customer, If the Customer does not exist print a message and return(exit the method)
thisCustomer = findCustomer(theCustomerID);
// Check the amount provided to see if it is less than zero. If it is less than zero then print a message and return(exit the method)
if( thisCustomer == null)
{
System.out.println("Customer " + theCustomerID + " does not exist. Returning!");
return;
}
// Update the customer balance by adding the amount to the existing customer balance.
double customerBalance = thisCustomer.getCustomerBalance() + theAmountToAdd;
thisCustomer.setCustomerBalance(customerBalance);
}
/**
* .checkOutApt.
* Parts b and c.
*/
public void rentOutApt(int theAptID, int theCustomerID, int theMonthsToRent)
{
// PART B:
// 1 Find the specific theAptID Apartment object and load it into thisApt.
// If null, print a message that the apt does not exist and return.
thisApt = findApartment(theAptID);
// 2 Verify that thisApt Apartment is available (not rented out to a customer).
// If not, print a message that the apt is already rented out and return.
if(thisApt.getAptRentalDate() == 0)
{
System.out.println("Apartment " + theAptID + " is available. Returning!");
return;
}
else
{
System.out.println("Apartment " + theAptID + " is rented out. Returning!");
return;
}
// 3 Find the specific theCustomerID object and load it into thisCustomer.
// If null, print a message that the customer does not exist and return.
thisCustomer = findCustomer(theCustomerID);
if(thisCustomer == null)
{
System.out.println("Customer " + theCustomerID + " does not exist. Returning!");
return;
}
// 4 Verify that thisCustomer Customer does not already have an apartment.
// If he or she does, print a message that the customer already has an apartment
// and return.
if(thisCustomer.getCustomerAptID() != 0)
{
System.out.println("*** Customer is already living in: " + customerAptID);
return;
}
// 5 Verify that the thisCustomer Customer has enough money to rent the apt.
// The initial payment from a customer to rent an apartmentis the sum of the calculated
// deposit based on customer credit rating (the getAptDepositAmount method)
// and the first month's rent.
//
// You will need to get the theCustomer’s balance and compare it to the sum of
// thisApt (getAptRent and getAptDepositAmount methods).
double customerBalance = thisApt.getAptDepositAmount(thisCustomer.getCustomerCreditRating()) + thisApt.getAptRent();
if(customerBalance > thisCustomer.getCustomerBalance())
{
System.out.println();
System.out.println("The customer does not have enough money.");
System.out.println("The customer is " + customerBalance + " short.");
System.out.println();
return;
}
// PART C:
// 6 Now check out theAptID Apt object to thisCustomer Customer object.
// In thisCustomer, set customerAptID to theAptID.
thisCustomer.setCustomerAptID(theAptID);
// In thisApt, set
// * aptCustomerID to theCustomerID
thisApt.setAptCustomerID(theCustomerID);
// In thisApt, set
// * aptDeposit to the deposit amount you find after using the
// getAptDepositAmount(int custCreditRating) method in Apartment Class
thisApt.setAptDeposit(thisApt.getAptDepositAmount(thisCustomer.getCustomerCreditRating()));
// set * aptMonthsRented theMonthsToRent
thisApt.setAptMonthsRented(theMonthsToRent);
// * aptRentalDate to currentDate
thisApt.setAptRentalDate(currentDate);
}
}

Lines 237-246 are:
if(thisApt.getAptRentalDate() == 0)
{
System.out.println("Apartment " + theAptID + " is available. Returning!");
return;
}
else
{
System.out.println("Apartment " + theAptID + " is rented out. Returning!");
return;
}
This is guaranteed to return. The output is different depending on the result of thisApt.getAptRentalDate(), but both conditions return.
Everything after that is therefore unreachable code. Since thisCustomer = findCustomer(theCustomerID); is on line 250, it is unreachable, as well as all other code in that method.

Related

How to write a remove method to get rid of object from arraylist

I'm trying to make a program in java that you can add people's birthdays, names, birthmonths, and birthyears. I'm having a hard time trying to come up with the code to remove an object from the arraylist here is the following code. How would I go about writing the removePerson method?
import java.util.ArrayList;
public class Analyzer {
// instance variables - replace the example below with your own
private final static int DAYS_PER_MONTH = 31;
private final static int MONTHS_PER_YEAR = 12;
private int[] birthDayStats;
private int[] birthMonthStats;
private ArrayList<Person> people;
/**
* Constructor for objects of class Analyzer
*/
public Analyzer() {
this.people = new ArrayList<Person>();
this.birthDayStats = new int[Analyzer.DAYS_PER_MONTH];
this.birthMonthStats = new int[Analyzer.MONTHS_PER_YEAR];
}
public void addPerson(String name, int birthDay, int birthMonth, int
birthYear) {
Person person = new Person(name, birthDay, birthMonth, birthYear);
if (person.getBirthDay() != -1 || person.getBirthMonth() != -1) {
people.add(person);
birthMonthStats[birthMonth - 1]++;
birthDayStats[birthDay - 1]++;
} else {
System.out.println("Your current Birthday is " + birthDay + " or "
+ birthMonth + " which is not a correct number 1-31 or 1-12 please " +
"put in a correct number ");
}
}
public void printPeople() { //prints all people in form: “ Name: Tom Month: 5 Day: 2 Year: 1965”
int index = 0;
while (index < people.size()) {
Person person = (Person) people.get(index);
System.out.println(person);
index++;
}
}
public void printMonthList() { //prints the number of people born in each month
// Sample output to the right with days being similar
int index = 0;
while (index < birthMonthStats.length) {
System.out.println("Month number " + (index + 1) + " has " +
birthMonthStats[index] + " people");
index++;
}
}
public Person removePerson(String name) {// removes the person from the arrayList
}
}
/**
* Removes the {#code Person} with the given {#code name} from the list
* #param name the {#code Person}'s name
* #return the {#code Person} removed from the list or {#code null} if not found
*/
public Person removePerson(String name) {
if (name != null) {
for (Iterator<Person> iter = people.iterator(); iter.hasNext(); ) {
Person person = iter.next();
if (name.equalsIgnoreCase(person.getName())) {
iter.remove();
return person;
}
}
}
return null;
}
See the java.util.Iterator#remove() method.
Tuesday learning bonus:
If you want to look for a name faster in your list, you should consider to use a java.util.Map implementation:
HashMap<String,Person> people;
You can add Person objects in a smart way in order to make your search case insensitive:
people.put(name.toLowerCase(), new Person(name, ...));
... and your removePerson method become:
public Person removePerson(String name) {
if (name != null)
name = name.toLowerCase();
return people.remove(name);
}
See the java.util.Map#remove() method.
If you are using Java 1.8. It's pretty simple way to do. This will remove Person having 'name' from your list.
people.removeIf(x -> name.equalsIgnoreCase(x.getName()));

private method call between classes

trying to get areasConnected to display. As you can see I have attemped (poorly I know) to substitute this method with the nextArea method. Will post the GameWorld class below this one. Please note that I DO NOT want someone to do the work for me, just point me in the right direction.
/**
* Auto Generated Java Class.
*/
import java.util.Scanner;
public class WereWolfenstein2D {
GameWorld gameOne = new GameWorld(true);
private boolean tracing = false;
Scanner sc = new Scanner(System.in);
String input, answer, restart;
int walk, current;
char area;
public void explain() {
System.out.print("You are a hunter, defend the village and capture the Werewolf by shooting it three times. ");
System.out.println("If you get bitten visit the village to be cured. " +
"If you get bitten twice you'll turn." +
"If none of the town folk survive, you lose. " +
"Now choose how what circumstances you're willing to work in.");
}
public void pickDifficulity(){
{
System.out.println("Easy, Normal or Hard?");
input = sc.nextLine();
input = input.toUpperCase();
if (input.equals("EASY")){
System.out.println(Difficulty.EASY);
}
else if (input.equals("NORMAL")) {
System.out.println(Difficulty.NORMAL);
}
else if (input.equals("HARD")) {
System.out.println(Difficulty.HARD);
}
}
}
public void preMove(){
System.out.println("current stats");
// no. of actions until dawn
gameOne.checkForDawn();
// current population
gameOne.getVillagePopulation();
// if they can hear village
gameOne.isVillageNear();
// if not bitten:
gameOne.getShotCount();
// current area no.
gameOne.getCurrentArea();
// number of connecting areas
// gameOne.nextArea(char direction);
//gameOne.areasConnected(int s1, int s2);
// no of times werewolf shot
// no. of bullets left
gameOne.getShotCount();
// if the player can smell the wolf
gameOne.werewolfNear();
}
public void pickMove(){
System.out.print("walk shoot, quit or reset?");
answer = sc.nextLine();
//walk
//if area not connected: alert
//if into village: alert that they are healed
//if containing wolf: altert they are bitten, if already bitten game ends
switch(answer) {
case "walk": System.out.println("Pick a direction to walk in south(s), east(e), north(n), west(w)");
current = gameOne.getCurrentArea(); //current area they are in
char direction = sc.next().charAt(current); //direction they wish to travel
// char area = sc.next().charAt(current);
char area1 = 's';
char area2 = 'e';
char area3 = 'n';
char area4 = 'w';
System.out.println("the area to the south is: " + gameOne.nextArea(area1));
System.out.println("the area to the east is: " + gameOne.nextArea(area2));
System.out.println("the area to the north is: " + gameOne.nextArea(area3));
System.out.println("the area to the west is: " + gameOne.nextArea(area4));
System.out.println(current +"<< >>" + direction);
System.out.println("pick again");
int newcurrent = direction;
direction = sc.next().charAt(newcurrent);
System.out.println(newcurrent + "<< new >>" + direction);
break;
case "shoot":
break;
case "quit": System.out.print("would you like to start again? (yes/no)");
restart = sc.nextLine();
if (restart.equals("yes")) {
gameOne.reset();
}
else {
System.out.println("Thanks for playing");
}
break;
case "reset": //gameOne.reset();
this.pickDifficulity();
break;
}
}
public void play() {
this.explain();
this.pickDifficulity();
this.preMove();
this.pickMove();
// gameOne.reset();
}
public void setTracing(boolean onOff) {
tracing = onOff;
}
public void trace(String message) {
if (tracing) {
System.out.println("WereWolfenstein2D: " + message);
}
}
}
GAMEWORLD CLASS>>>
public class GameWorld {
// Final instance variables
public final int NIGHT_LENGTH = 3; // three actions until dawn arrives (day is instantaneous)
private final int MAX_SHOTS_NEEDED = 3; // successful hits required to subdue werewolf
//This map is _deliberately_ confusing, although it actually a regular layout
private int[] east = {1,2,0,4,5,3,7,8,6}; // areas to east of current location (index)
private int[] west = {2,0,1,5,3,4,8,6,7}; // areas to west of current location (index)
private int[] north = {6,7,8,0,1,2,3,4,5}; // areas to north of current location (index)
private int[] south = {3,4,5,6,7,8,0,1,2}; // areas to south of current location (index)
private int numAreas = south.length; // number of areas in the "world"
// Non-final instance variables
private int currentArea; // current location of player
private int villagePos; // area where the village is located
private int wolfPos; // area where the werewolf can be found
private Difficulty level; // difficulty level of the game
private int villagerCount; // number of villagers remaining
private int stepsUntilDawn; // number of actions until night falls
private boolean isBitten; // is the player currently bitten and in need of treatment?
private int hitsRemaining; // number of shots still needed to subdue the werewolf
private Random generator; // to use for random placement in areas
private boolean tracing; // switch for tracing messages
/**
* Creates a game world for the WereWolfenstein 2D game.
* #param traceOnOff whether or not tracing output should be shown
*/
public GameWorld(boolean traceOnOff) {
trace("GameWorld() starts...");
generator = new Random();
generator.setSeed(101); //this default setting makes the game more predictable, for testing
setTracing(traceOnOff); //this may replace random number generator
trace("...GameWorld() ends");
}
/**
* Returns the number of the current area.
* #return which area number player is within
*/
public int getCurrentArea() {
trace("getCurrentArea() starts... ...and ends with value " + currentArea);
return currentArea;
}
/**
* Returns the number of shot attempts, formatted as "total hits/total required"
* #return the fraction of shots that have hit the werewolf (out of the required number of hits)
*/
public String getShotCount() {
String count; // formatted total
trace("getShotCount() starts...");
count = (MAX_SHOTS_NEEDED - hitsRemaining) + "/" + MAX_SHOTS_NEEDED;
trace("getShotCount() ...ends with value " + count);
return count;
}
/**
* Returns the current number of villagers.
* #return the villager count, >= 0
*/
public int getVillagePopulation() {
return villagerCount;
}
/**
* Returns the number of actions remaining until dawn arrives.
* #return actions remaining until dawn event
*/
public int getActionsUntilNight() {
return stepsUntilDawn;
}
/**
* Randomly determines a unique starting location (currentArea), village
* position (villagePos) and werewolf position (wolfPos).
* #param difficulty - the difficulty level of the game
* #return the starting location (area)
*/
public int newGame(Difficulty difficulty) {
trace("newGame() starts...");
level = difficulty;
//determine village location and initialise villagers and night length
villagePos = generator.nextInt(numAreas);
stepsUntilDawn = NIGHT_LENGTH;
villagerCount = level.getVillagerCount();
// determine player's position
if (level.getPlayerStartsInVillage()) {
//place player in village
currentArea = villagePos;
} else {
//pick a random location for player away from the village
do {
currentArea = generator.nextInt(numAreas);
} while (currentArea == villagePos);
}
trace("player starts at " + currentArea);
// determine werewolf's position
trace("calling resetTargetPosition()");
resetWolfPosition();
// define player's status
trace("player is not bitten");
isBitten = false;
trace("werewolf is not hit");
hitsRemaining = MAX_SHOTS_NEEDED;
trace("...newGame() ends with value " + currentArea);
return currentArea;
}
/** Randomly determines a unique location for werewolf (wolfPos). */
private void resetWolfPosition() {
int pos; // werewolf position
trace("resetWolfPosition() starts...");
pos = generator.nextInt(numAreas);
while (pos == currentArea || pos == villagePos) {
trace("clash detected");
// avoid clash with current location
pos = generator.nextInt(numAreas);
}
wolfPos = pos;
trace("werewolf position is " + wolfPos);
trace("...resetWolfPosition() ends");
}
/**
* Returns the nearness of the werewolf.
* #return Status of werewolf's location
* BITTEN: if player is currently bitten (and delirious)
* NEAR: if werewolf is in a connected area
* FAR: if werewolf is elsewhere
*/
public Result werewolfNear() {
trace("werewolfNear() starts");
if (isBitten) {
trace("werewolfNear(): player is still delirious from a bite so cannot sense nearness of werewolf");
return Result.BITTEN;
}
trace("werewolfNear() returning result of nearnessTo(" + wolfPos + ")");
return nearnessTo(wolfPos);
}
/**
* Returns true if the village is near the player (in an adjacent area),
* false otherwise.
* #return true if the player is near (but not in) the village, false otherwise.
*/
public boolean isVillageNear() {
trace("villageNear() starts and returns result of nearnessTo(" + villagePos + ") == Result.NEAR");
return nearnessTo(villagePos) == Result.NEAR;
}
/**
* Returns the nearness of the player to the nominated area.
* #param area the area (werewolf or village) to assess
* #return Nearness of player to nominated area
* NEAR: if player is adjacent to area
* FAR: if player is not adjacent to the area
*/
private Result nearnessTo(int area) {
Result closeness; // closeness of player to area
trace("nearnessTo() starts...");
if ((east[currentArea] == area) ||
(west[currentArea] == area) ||
(north[currentArea] == area) ||
(south[currentArea] == area))
{
// player is close to area
closeness = Result.NEAR;
trace("area is close");
} else {
// player is not adjacent to area
closeness = Result.FAR;
trace("area is far");
}
trace("...nearnessTo() ends with value " + closeness);
return closeness;
}
/**
* Try to move the player to another area. If the move is not IMPOSSIBLE
* then the number of actions remaining before dawn arrives is decremented.
* #param into the area to try to move into
* #return Result of the movement attempt
* SUCCESS: move was successful (current position changed)
* VILLAGE: move was successful and player has arrived in the village (and is not longer bitten)
* BITTEN: move was successful but player encountered the werewolf
* FAILURE: move was successful but already bitten player encountered the werewolf again
* IMPOSSIBLE: move was impossible (current position not changed)
*/
public Result tryWalk(int into) {
Result result; // outcome of walk attempt
trace("tryWalk() starts...");
if (areasConnected(currentArea, into)) {
trace("move into area " + into );
currentArea = into;
if (currentArea != wolfPos) {
// werewolf not found
trace("werewolf not encountered");
result = Result.SUCCESS;
if (currentArea == villagePos) {
isBitten = false;
result = Result.VILLAGE;
}
} else {
// werewolf encountered
if (isBitten) {
trace("werewolf encountered again");
result = Result.FAILURE;
} else {
// not bitten
trace("werewolf encountered");
result = Result.BITTEN;
isBitten = true;
resetWolfPosition();
}
}
stepsUntilDawn--; //one more action taken
} else { // area not connected
trace("move not possible");
result = Result.IMPOSSIBLE;
}
trace("...tryWalk() ends with value " + result);
return result;
}
/**
* Try to shoot a silver bullet at the werewolf from the current area.
* If the shot is not IMPOSSIBLE then the number of actions remaining
* before dawn arrives is decremented.
* #param into the area to attempt to shoot into
* #return status of attempt
* CAPTURED: werewolf has been subdued and captured
* SUCCESS: werewolf has been hit but is not yet captured
* VILLAGE: the shot went into the village and a villager has died
* FAILURE: werewolf not present
* IMPOSSIBLE: area not connected
*/
public Result shoot(int into) {
Result result; // outcome of shooting attempt
trace("shoot() starts...");
if (areasConnected(currentArea, into)) {
// area connected
trace("shoot into area " + into );
if (into == villagePos) {
result = Result.VILLAGE;
villagerCount--;
trace("shot into village");
} else if (into != wolfPos) {
// not at werewolf location (but at least didn't shoot into the village!)
result = Result.FAILURE;
trace("werewolf not present");
} else {
// at werewolf location
hitsRemaining--;
if (hitsRemaining == 0) {
// last hit required to subdue the werewolf
trace("werewolf subdued and captured");
result = Result.CAPTURED;
} else {
// not the last shot
result = Result.SUCCESS;
if (level.getWolfMovesWhenShot()) {
resetWolfPosition();
}
trace("werewolf found but not yet captured");
}
}
stepsUntilDawn--; //one more action taken
} else {
// not at valid location
result = Result.IMPOSSIBLE;
trace("area not present");
}
trace("...shoot() ends with value " + result);
return result;
}
/**
* Checks if there are no more actions left until dawn arrives. If dawn is
* here then decrements the number of villagers, repositions the werewolf
* and resets the number of actions until dawn arrives again. Returns true
* if dawn occurred, false if it did not.
* #return true if dawn just happened, false if has not yet arrived
*/
public boolean checkForDawn() {
if (stepsUntilDawn == 0) {
if (villagerCount > 0) { //dawn may arrive after shooting the last villager
villagerCount--;
}
stepsUntilDawn = NIGHT_LENGTH;
resetWolfPosition();
return true;
}
return false;
}
/**
* Returns true if areas s1 and s2 are connected, false otherwise.
* Also returns false if either area is an invalid area identifier.
* #param s1 the first area
* #param s2 the second area
* #return true if areas are connected, false otherwise
*/
private boolean areasConnected(int s1, int s2) {
if (Math.min(s1, s2) >= 0 && Math.max(s1, s2) < numAreas) { //valid areas...
//...but are they connected?
return east[s1] == s2 || north[s1] == s2 || west[s1] == s2 || south[s1] == s2;
}
//Either s1 or s2 is not a valid area identifier
return false;
}
/**
* Determine ID number of an adjacent area given its direction from the
* current area.
* #param direction the direction to look (n for north, e for east, s for south, w for west)
* #return number of the area in that direction
* #throws IllegalArgumentException if direction is null
*/
public int nextArea(char direction) {
int nextIs; // area number of area in indicated direction
//Valid values
final char N = 'n', E = 'e', S = 's', W = 'w';
trace("nextArea() starts...");
// examine adjacent areas
switch (direction) {
case N: trace("determining number of area to the north");
nextIs = north[currentArea];
break;
case E: trace("determining number of area to the east");
nextIs = east[currentArea];
break;
case S: trace("determining number of area to the south");
nextIs = south[currentArea];
break;
case W: trace("determining number of area to the west");
nextIs = west[currentArea];
break;
default: throw new IllegalArgumentException("Direction must be one of " + N + ", " + E + ", " + S + " or " + W);
}
trace("...nextArea() ends with value for '" + direction + "' of " + nextIs);
return nextIs;
}
/** Resets all game values. */
public void reset() {
trace("reset() starts...");
// reset all game values
trace("resetting all game values");
newGame(level); //start a new game with the same difficulty
trace("...reset() ends");
}
/**
* Turn tracing messages on or off. If off then it is assumed that
* debugging is not occurring and so a new (unseeded) random number
* generator is created so the game is unpredictable.
* #param shouldTrace indicates if tracing messages should be displayed or not
*/
public void setTracing(boolean shouldTrace) {
if (! shouldTrace) { // not tracing so get an unseeded RNG
generator = new Random();
}
tracing = shouldTrace;
}
/**
* Prints the given tracing message if tracing is enabled.
* #param message the message to be displayed
*/
public void trace(String message) {
if (tracing) {
System.out.println("GameWorld: " + message);
}
}
}
You can use reflection. Actually, it's the only way out if you want to directly access the private methods/fields of an object or a class.

removeZero() method when creating linkedlist?

I am creating a LinkedList from scratch, in the form of a train. So I have a class called Domino which creates each node, and then I have the class Train, which includes the add, size, remove etc methods. My problem is:
removeZeros() method: I cannot have any parameters, but I must delete all the nodes with zeros in them. What my program does instead is find all the zeros in the list, and delete all the nodes up until there are no more zeros. The zeros were added in a client class.
here is my Train class:
public class Train{
private Domino engine;
private Domino caboose;
private int insertS;
public Train(){
engine = null;
caboose = engine;
}
/** WHERE IM HAVING TROUBLE
* removeZero() - remove any Dominos from the train that have one or more zero spots
* while maintaining the linked list structure.
*/
// method is now just getting the spot1 0 and printing that
public void removeZero(){
Domino current = engine;
Domino hold = caboose.next;
while (current != hold) {
if(current.spot1 == 0 ||current.spot2 == 0){
current = current.next;
engine = current;
System.out.println("b " + engine);
}else{
current = current.next;
}
}
public String toString(){
String ts = "{ empty }";
if (engine == null) {
return ts;
} else {
Domino hold = engine;
ts = "{ ";
while (hold != caboose) {
ts += hold + ", ";
hold = hold.next;
}
ts += hold + " }";
}
return ts;
}
/**
*
* add(spot1, spot2) - add a Domino to the end of the Train with the given spots
*/
public void add(int spot1, int spot2){
if (engine == null) {
engine = new Domino(spot1,spot2);
caboose = engine;
} else {
caboose.next = new Domino(spot1, spot2, null,caboose);
//tail.next.back = tail;
caboose = caboose.next;
}
}
}
/**
* reversePrint() - like toString, but provides a String that lists
* all of the Dominos that are in the Train in reverse order
*/
public String reversePrint () {
Domino hold = caboose;
String reverse = "{ empty }";
if (engine == null) {
System.out.println(reverse);
} else {
reverse = "{ ";
while (hold != engine){
reverse += hold + ", ";
hold = hold.back;
}
reverse += hold + " }";
}
return reverse;
}
/**
* size() - return the number of Dominos in the Train
*/
public int size(){
int count = 0;
Domino hold = engine;
while(hold != null){
hold = hold.next;
count++;
}
return count;
}
/** insert(spot1, spot2, next, back) - insert a Domino in the middle of
* the Train where spot2 is the same as the spot1 of the next Domino and spot1
* is the same as spot2 of the previous Domino.
* (private)
*/
private void insert(int spot1,int spot2){
if (!(insertS == search)) {
Domino hold = engine;
while (hold != caboose) {
if (hold.spot1 == search) {
Domino newDom = new Domino(spot1, spot2, null,caboose);
hold.next = newDom;
newDom.next.back = newDom;
hold = hold.next;
} else {
hold = hold.next;
}
}
if (hold.spot2 == search) {
add(spot1, spot2);
}
} else {
System.out.println(" ** Error Inserting these values will cause an infinite loop:");
System.out.println(" * * * " + insertS + " and " + search + " * * *");
}
}
/**
* build() - scans through the Train creating links, using insert(spot1, spot2), between
* existing Dominos where the second spot of the first Domino does not match the
* first spot of the second domino, no param
*/
public void build(){
insert(search, insertS);
}
}
here is my Domino class:
public class Domino{
public int spot1; // the leading half how many spots it has
public int spot2; // the trailing half how many spots it has
public Domino next; // a link to the next Domino (type)?
public Domino back; // a link to the previous Domino
private int zero;
/**
* Constructor
* Creates null Domino
*
*/
public Domino(){
this(0,0 , null, null);
}
/**
* Constructor
* a constructor for Domino with given spots
*/
public Domino( int spot1, int spot2){
this(spot1,spot2, null, null);
}
/**
* Constructor
* #param: all fields
* setting variables
*/
public Domino(int spot1, int spot2, Domino next, Domino back){
this.spot1 = spot1;
this.spot2 = spot2;
this.next = next;
this.back = back;
}
/**
* toString(): prints out single Domino
*
*/
public String toString(){
if(this == null){
return("[empty]");
}else{
return("[ " + spot1 + " | "+ spot2 + "]");
}
}
}
I've really been stuck on this for the past day or so and can't seem to figure it out. Any help would be great. If you need the client code please say so. Thanks!
In the case of encountering a zero domino, you assign engine to be the current domino. As engine is the head of the list, this is equivalent to deleting all the items preceding the one containing a zero. Deletion in linked list is usually accomplished by something like:
toDelete.back.next = toDelete.next;
toDelete.next.back = toDelete.back
where toDelete is a Domino object with a zero in this case. As no domino now has a reference to the toDelete domino, it is essentially deleted.

Issues with toString and Inheritance [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have I am having trouble figuring out an issue I have with a toString method. toString () must be changed so that it prints all the relevant information about the Player (and collection of
Items). Subclasses should overwrite the superclass toString (), but still use the toString ()
from the super class implementation when this reduces code duplication.
How do I go about doing this?
Player class:
import java.util.HashMap;
public class Player extends Character {
private String name;
private String type;
public static HashMap<String, Item> backpack;
private int maxCarryingCapacity;
/**Constructor
* Creates a player with health 100, an empty backpack
* and max carrying capacity 100
*
* #param nick the players name
* #param type the players type
* #param minDamage players minimum damage
* #param maxDamage players maximum damage
*/
public Player(String name, String type, int minDamage, int maxDamage) {
super(name, minDamage, maxDamage);
setName(name);
setType(type);
health = 100;
gold = 100;
backpack = new HashMap<String, Item>();
maxCarryingCapacity = 100;
setMinDamage(minDamage);
setMaxDamage(maxDamage);
}
/**
* Use an item in backpack
* #param itemName
* #return true if item is used, and false
* if there's no item by that name in the backpack
*/
public boolean useItem(String itemName) {
Item item = findItem(itemName);
if(item != null) {
System.out.println(name + " " + item.getAction() + " " + item.getName());
return true;
} else {
return false;
}
}
public boolean equipItem(String itemToEquip) {
Item item = findItem(itemToEquip);
if (item != null) {
this.minDamage = this.minDamage + item.getBonus();
return true;
} else {
return false;
}
}
/**
* Adds item to players inventory. An
* item can only be bought if the total weight does not
* exceed the players carrying capacity
* #param item
* #return true if the item is bought
*/
public boolean addItem(Item item) {
int totalWeight = totalWeight() + item.getWeight();
if(totalWeight <= maxCarryingCapacity){
backpack.put(item.getName(), item);
return true;
} else {
return false;
}
}
/**
* Find item in backpack
*
* #param name of item
* #return item, or null if item is not int the backpack
*/
public Item findItem(String itemName) {
return backpack.get(itemName);
}
/**
* Removes item from player's backpack and
* add item value to player's gold
*
* #param name of item to sell
* #return true if successful
*/
public boolean sellItem(String itemToSell) {
Item item = findItem(itemToSell);
if(item != null) {
gold += item.getValue();
backpack.remove(item.getName());
return true;
} else {
return false;
}
}
/**
* #return true if the player is alive
*/
public boolean isAlive() {
if(health > 0 && health <= 100) {
return true;
} else return false;
}
/**
* #return a string with player information
*/
#Override
public String toString() {
String string = "Name: " + name + " Type: " + type + "\n";
if(isAlive()) {
string += "Is alive with health: " + health;
} else {
string += "Is dead.";
}
string += "\n"+ name + "'s backpack contains the following items: \n";
for(Item item : backpack.values()) {
string += item;
}
return string;
}
/**
* #return the players type
*/
public String getType() {
return type;
}
/**Sets the players type
* Valid types: Mage, Ranger, Warrior, Rogue
* #param newType
*/
public void setType(String newType) {
newType = newType.toLowerCase().trim();
if(newType.equals("mage") || newType.equals("ranger") || newType.equals("warrior") || newType.equals("rogue")){
this.type = newType;
} else {
this.type = "Unspecified";
}
}
/**
* #param item
* #return current carrying weight
*/
private int totalWeight() {
int tempWeight = 0;
for(Item itemInBackpack : backpack.values()) {
tempWeight += itemInBackpack.getWeight();
}
return tempWeight;
}
public int attack(Monster currentEnemy) {
int damage = Utils.random(minDamage, maxDamage+1);
currentEnemy.changeHealth(-damage);
return damage;
}
}
The Character superclass (abstract class):
abstract class Character
{
public String name;
public static int health;
public int gold;
public int minDamage;
public int maxDamage;
public Character(String name, int minDamage, int maxDamage) {
setName(name);
health = 100;
gold = 100;
setMinDamage(minDamage);
setMaxDamage(maxDamage);
}
public Character () {
}
/**
* Changes the character health
* The health can not be less the 0 or "less than or euqal to" 100.
* #param healthPoints
*/
public void changeHealth(int healthPoints) {
int temp = health + healthPoints;
if(temp > 100) {
health = 100;
} else if (temp <= 0) {
health = 0;
} else {
health = temp;
}
}
/**
* #return true if the character is alive
*/
public boolean isDead() {
if(health > 0 && health <= 100) {
return false;
} else return true;
}
/**
* #return the characters name
*/
public String getName() {
return name;
}
/**Set to Unspecified if the string is empty
* #param name
*/
public void setName(String name) {
this.name = Utils.checkString(name);
}
/**
* #return the characters health
*/
public static int getHealth() {
return health;
}
/**
* Get minimum damage
* #return minimum damage
*/
public int getMinDamage() {
return minDamage;
}
/**
* Set minimum damage, if minDamage >= 5, minDamage is otherwise set to 5
* #param minimum Damage
*/
public void setMinDamage(int minDamage) {
this.minDamage = minDamage >= 5 ? minDamage : 5;
}
/**
* Get maximum damage
* #return maximum damage
*/
public int getMaxDamage() {
return maxDamage;
}
/**
* Set maximum damage, if maxDamage <= minDamage, maxDamage is set to minDamage +5
* #param maximum damage
*/
public void setMaxDamage(int maxDamage) {
this.maxDamage = maxDamage <= minDamage ? minDamage+5 : maxDamage;
}
/**
* Get money
* #return amount of money
*/
public int getGold() {
return gold;
}
/**
* Set money
* #param amount of money
*/
public void setGold(int gold) {
this.gold = Utils.checkNegativeInt(gold);
}
}
In general, given two classes, A and B and if class B extends A then B has all of the properties of A plus some of its own. Therefore, when you implement B's toString() method, you should do this:
#Override
public String toString() {
String newStuff = // description of the new variables
return super.toString() + newStuff;
// Now describe the elements of B that aren't included in A
}
However, your implementation doesn't give a basic toString() method for Character so calling super.toString() is equivalent to calling Object.toString(). Therefore you should first implement toString for your Character abstract class.
for example, you could do:
public String toString() {
return "Name: " + name + "\nHealth: " ... all the attributes
}
There is a lot of redundancy in your code though. First of all, both your Character class and your Player class have the same name variable, which goes against the point of inheritance. In fact, you never even use Player's name variable.
also, there is no point in creating getter/setter methods in Character if all the variables are declared public anyways. It is better to make them private and use getter/setters though.
Your abstract superclass has name and health, but not type or backpack. (I just noticed, thanks to user2573153's answer, that you also have name in your Player class; I don't think you want that.)
I think the first thing you want to do is to answer this question: Suppose you create a new subclass, and you don't override toString(), and then an object gets printed out. What would you want to see printed out?
Maybe you want the name and health printed out. So you can declare this in your abstract Character class (which I think shouldn't be called Character because java.lang already has a Character):
#Override
public String toString() {
String string = "Name: " + name + "\n";
if(isAlive()) {
string += "Is alive with health: " + health;
} else {
string += "Is dead.";
}
return string;
}
Then, if you wanted toString() in Player or Monster to add something to the end of that, it would be pretty easy:
#Override
public String toString() {
String string = super.toString(); // here's where you call the superclass version
string += "\n Type: " + type;
string += "\n"+ name + "'s backpack contains the following items: \n";
for(Item item : backpack.values()) {
string += item;
}
return string;
}
In your actual code, however, you want the Type information inserted in the middle of the string that the superclass toString() would return. That makes things tougher. I can think of two ways to handle it. One would be to use some string manipulation methods to search for \n and insert the "Type" string in there. But I think it's better to split the string into two methods. You can put these in your Character class:
protected String nameString() {
return "Name: " + name;
}
protected String healthString() {
if(isAlive()) {
return "Is alive with health: " + health;
} else {
return "Is dead.";
}
}
Now, your toString() in Character might look like
#Override
public String toString() {
return nameString() + "\n" + healthString();
}
and in Player:
#Override
public String toString() {
return nameString() + " Type: " + type + "\n" + healthString();
}
and you still get to avoid duplicated code. (You don't need to say super.nameString() because your subclass will automatically inherit it and you don't plan to override it.)
Superclass methods aren't automatically called. When you override toString() in Player and you call toString() on an instance of Player the only code that gets run is Player's toString().
If you want to include the toString() of Character in your toString() of Player you need to make that explicit by calling super.toString() in Player's toString().
Your Player implementation of toString() could be amended to include my recommendation as follows:
/**
* #return a string with player information
*/
#Override
public String toString() {
String string = "Name: " + name + " Type: " + type + "\n";
if(isAlive()) {
string += "Is alive with health: " + health;
} else {
string += "Is dead.";
}
string += "\n"+ name + "'s backpack contains the following items: \n";
for(Item item : backpack.values()) {
string += item;
}
return super.toString() + string;
}
The salient part of this is changing:
return string;
To:
return super.toString() + string;

Getting error on JUnit test

So the assignment my professor has given does not allow me to edit anything on the JUnit test because our class that we have written has to match with her Javadoc. So everything is working fine except I am getting an error and 3 failures. No matter what I try I can't seem to fix these. How can I fix an error and make all tests pass without changing the JUnit Test, I just can't spot the error. Basically in general how do you get rid of errors in JUnits and failures while not changing the JUnit.
Here is my company class
/**
* #author Amin Oskoui
* This is the company class aka the data manager which contains the majority of the methods and holds the arraylist.
*/
import javax.swing.*;
import java.util.*;
public class Company {
private static final long serialVersionUID = 1L;//ensuring that the class corresponds with a serialized object
Employee a;
private String companyName;//name of company
final int maxCompanies = 2, maxEmployees = 7, maxSales = 1, maxDesign = 2, maxManufacturing = 4;
private static int numberOfCompanies;//the number of companies
private int numEmployees;//the number of employees
public int numDesign;//the number of employees in design
private int numManufacturing;// the number of employees in manufacturing
private int numSales;//the number of employees in sales
private ArrayList<Employee> employeeList;
/**
*
* #param cn parameter for cn
*/
public Company(String cn){
numEmployees = 0;
numSales = 0;
numDesign = 0;
numManufacturing = 0;
companyName = cn;
numberOfCompanies++;
employeeList = new ArrayList<Employee>();
}
/**
*
* #param employeeCount parameter for employeeCount
* #param numDesign parameter for numDesign
* #param numSales parameter for numSales
* #param numManufacturing parameter for numManufacturing
* #param companyName parameter for companyName
*/
public Company(int employeeCount, int numDesign, int numSales, int numManufacturing, int numOfCompanies) {
this.numEmployees = employeeCount;
this.numDesign = numDesign;
this.numSales = numSales;
this.numManufacturing = numManufacturing;
this.companyName = companyName;
numberOfCompanies++;
employeeList = new ArrayList<Employee>();
}
/**
*
* #param fName parameter for fName
* #param lName parameter for lName
* #param parameter for p
* #return
*/
public String addEmployee(String fName, String lName, String p) {
/**
* #return returns a string with an error message
*/
if (numEmployees >= maxEmployees) {
return "There is already 7 employees\nEmployee not added";
}
switch (p) {//switch statement for each case
case "Sales":
//if there's less than 1 salesman, add them to the list
if (numSales < maxSales) {
Employee employee = new Employee(fName, lName, p);
employeeList.add(employee);
numSales++;
numEmployees++;
return "Salesperson added successfully!";
}
else {
/**
* #return returns a string with an error message
*/
return "There is already a sales person\nEmployee not added";
}
case "Design":
if (numDesign < maxDesign) {
Employee employee = new Employee(fName, lName, p);
employeeList.add(employee);
numDesign++;
numEmployees++;
return "Designer added successfully!";
}
else {
/**
* #return returns a string with an error message
*/
return "There are already two design persons\nEmployee not added";
}
case "Manufacturing":
if (numManufacturing < maxManufacturing){
Employee employee = new Employee(fName, lName, p);
employeeList.add(employee);
numManufacturing++;
numEmployees++;
return "Manufacturer added successfully!";
}
else {
/**
* #return returns a string with an error message
*/
return "There are already four manufacturing persons\nEmployee not added";
}
}
/**
* #return return statement just to make sure the program operates properly.
*/
return "This should never appear";
}
public static int getNumCompanies(){//return the number of companies
return numberOfCompanies;
}
public int getNumEmployees(){//get the number of employees
return numEmployees;
}
public String printCompany(){//print the company with all of the positions
String companyPrint = companyName + "\n";
return companyName;
}
public String employeeListString() {
String s;
s = companyName + "\n";
for (Employee e : employeeList) {
s += e + "\n";
}
return s;
}
/**
* #param s passes the String s
*/
public void setCompanyName(String s) {
companyName = s;
}
public void clearEmployees() {
numEmployees = numDesign = numManufacturing = numSales = 0;
employeeList.clear();
}
#Override
public String toString() {//converts everything to a string
return "Company [position=" + ", companyName=" + companyName
+ ", employees=" + employeeList + ", numEmployees=" + numEmployees
+ ", numDesign=" + numDesign + ", numManufacturing="
+ numManufacturing + ", numSales=" + numSales + "]";
}
}
And here is the JUnit test for it.
import static org.junit.Assert.*;
import java.util.Scanner;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* This is a JUnit test program to test the Company.
* The following classes must be defined and implemented:
* Position - enumeration
* Employee - data element
* Company - data manager
* #author Professor Myers changed by Prof. Justh
*
*/
public class CompanyTester {
/** A Company object reference used for testing */
Company company, studentCompany;
#Before
/** This method is run before each individual test
* Creates an object of Company and adds three
* Employees to the Company
*/
public void setUp() throws Exception {
company = new Company("New Source");
company.addEmployee("John", "Smith","Manufacturing");
company.addEmployee("Bob", "Brown", "Manufacturing");
company.addEmployee("Harold", "Jones", "Sales");
company.addEmployee("Betty","Boop", "Design");
//STUDENT: Create your own instance of company (studentCompany) and add employees.
//You will use this studentCompany instance in the STUDENT test methods
}
#After
/** This method is run after each individual test
* It sets the Company reference to null so the garbage
* collector can reclaim the memory used for the
* Company object
* #throws Exception
*/
public void tearDown() throws Exception {
company = null;
}
#Test
/**
* Test to
* 1. check if the number of employees is originally 4
* 2. Add another employee, and check if number of employees is 5
*
*/
public void testGetNumEmployees() {
assertEquals(4,company.getNumEmployees());
company.addEmployee("George", "Jones", "Design");
assertEquals(5, company.getNumEmployees());
company.addEmployee("Susie", "Smith", "Manufacturing");
assertEquals(6, company.getNumEmployees());
company.addEmployee("Susie", "Smiley", "Manufacturing");
assertEquals(7, company.getNumEmployees());
}
#Test
/**
* Use the studentCompany instance
* Test to
* 1. check the original number of employees
* 2. Add another employee, and check if number of employees has increased by 1
*
*/
public void testGetNumEmployeesSTUDENT() {
assertEquals(4,company.getNumEmployees());
company.addEmployee("John", "Mayhew", "Design");
assertEquals(5, company.getNumEmployees());
company.addEmployee("Sally", "Sams", "Manufacturing");
assertEquals(6, company.getNumEmployees());
company.addEmployee("Max", "Schmidt", "Manufacturing");
assertEquals(7, company.getNumEmployees()); }
#Test
/**
* Test to
* 1. add 3 new Employees as a manufacturing person
* check if recognizes there are already 4 manufacturing persons
* 2. add a new employee as a sales person
* check if recognizes there is already a a sales person
* 3. add 2 new employee as a design person
* check if recognizes there is already 2 design persons
*/
public void testAddEmployee() {
String result;
//add another designer - No problem, should return null
result = company.addEmployee("Bobby", "Match", "Design");
assertEquals(null, result);
//add another designer - already 2 designers - return error message
result = company.addEmployee("Albert","Pine", "Design");
assertEquals("There are already two design persons\nEmployee not added", result);
//add another sales person - already 1 sales person - return error message
result = company.addEmployee("Susie", "Smith", "Sales");
assertEquals("There is already a sales person\nEmployee not added", result);
//add another manufacturer - No problem, should return null
result = company.addEmployee("Benedict", "Cumberbatch", "Manufacturing");
assertEquals(null, result);
//add another manufacturer - No problem, should return null
result = company.addEmployee("Martin", "Freeman", "Manufacturing");
assertEquals(null, result);
//add another manufacturer - already 4 manufacturers - return error message
result = company.addEmployee("Andrew", "Scott", "Manufacturing");
assertEquals("There are already four manufacturing persons\nEmployee not added", result);
}
#Test
/**
* Test to
* 1. add a new Employees as a manufacturing person
* check if recognizes there are already 4 manufacturing persons
* 2. add a new employees as a sales person
* check if recognizes there is already a a sales person
* 3. add new employees as a design person
* check if recognizes there are already 2 design persons
*/
public void testAddEmployeeSTUDENT() {
fail("Test not yet implemented");
}
#Test
/**
* Test to:
* 1. Check if the company name is on the first line
* 2. Check if John is on the second line
* 3. Check if Bob is on the third line
* 4. Check if Harold is on the fourth line
* 5. Check if Betty is on the fifth line
*/
public void testPrintCompany() {
String result = company.printCompany();
Scanner company = new Scanner(result);
assertEquals("New Source",company.nextLine());
//extract three Employees
assertEquals("John", company.next());
company.nextLine(); //Smith Position design (rest of line)
assertEquals("Bob", company.next());
company.nextLine(); //Brown Position manufacturing (rest of line)
assertEquals("Harold",company.next()); //Harold
company.nextLine(); //Jones Position Sales (rest of line);
assertEquals("Betty",company.next());
}
#Test
/**
* Test to:
* 1. Check if the company name is on the first line
* 2. Check if other employees are in order as entered
*/
public void testPrintCompanySTUDENT() {
fail("Test not yet implemented");
}
#Test
public void testMoreThan1company()
{
//created company and studentCompany instances
assertEquals(2, Company.getNumCompanies());
//create another company instance
Company company2 = new Company("New Company");
assertEquals(3, Company.getNumCompanies());
}
}
Here is the employee class
/**
* #author This is the employee class which is also the data element in charge of holding the information for the employee entered by the user.
*/
import javax.swing.JOptionPane;
public class Employee {
private String fName;
private String lName;
private String p;
public Employee(String fName, String lName, String p) {
this.fName = fName;
this.lName = lName;
this.p = p;
}
public String getFName(){
return fName;
}
public String getLName(){
return lName;
}
public String getP(){
return p;
}
public String toString(){
return fName + " " + lName + " " + "Position: " + p;
}
}
Look through the tests. Look at what they expect your program to produce. Then look at what your program is producing. For example, this is from one of the tests:
String result;
//add another designer - No problem, should return null
result = company.addEmployee("Bobby", "Match", "Design");
assertEquals(null, result);
That means the test expects addEmployee() to return null when it is successful. Is that what your addEmployee() method does?
Now do that for all the tests and you'll have found all your errors.
Also, look at the output from jUnit. When an assert fails it gives you a pretty good idea why. It will say something like, expected xxxxx to be yyyyy but it was zzzzz instead.

Categories