Issues with toString and Inheritance [closed] - java

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;

Related

How to write constructor that will accept 1 of 3 String values that I choose in the case (morning, evening, night)?

this is a subclass and am trying to shifts variable to accept only 1 of 3 values, that's morning evening night am a newbie so please forgive me for such a simple question
public class PartTimeStaffHire extends StaffHire
{
// instance variables - replace the example below with your own
private int workingHour
private double wagesPerHour
private String shifts;
private boolean terminated
This is subclass of StaffHire and accept all this variables and the last one am trying to accept only 1 of this 3 values
/**
* Constructor for objects of class PartTimeStaffHire
*/
public PartTimeStaffHire(int vacancy, String designation1, String typeofjob,
String staffName1, String joinDate, String qualification1, String appointed,
boolean joined, int hoursPerDay, double wagePerHour, String shift)
{
super(vacancy, designation1, typeofjob, staffName1, joinDate,
qualification1, appointed, joined);
workingHour = hoursPerDay;
wagesPerHour = wagePerHour;
shifts = shift;
if( shifts == "morning") {
shifts = "morning";
}
else if(shifts == "evening") {
shifts = "evening";
}
else if(shifts == "night") {
shifts = "night";
}
else {
System.out.println("Choose (morning, evening, night)" );
}
//(morning, evening, night)
}
public String shift()
{
if( shifts == "morning") {
shifts = "morning";
}
else if(shifts == "evening") {
shifts = "evening";
}
else if(shifts == "night") {
shifts = "night";
}
else {
System.out.println("Choose (morning, evening, night)" );
}
return shifts;
}
/**
* An example of a method - replace this comment with your own
*
* #param y a sample parameter for a method
* #return the sum of x and y
*/
public void print()
{
super.print();
System.out.println("The yearly salary is " + wagesPerHour);
System.out.println("Weekly working hours are " + workingHour;
System.out.println("##################" + shifts);
}
}
thanks in advance
If you know the possible values of a type, an enum is what you want to use.
So in this case you can create an enum Shift with the three possible constants:
public enum Shift {
MORNING,
EVENING,
NIGHT;
//this lets you convert a String such as `morning` to an enum constant
//if the enum not not one of the 3 constants (ignoring the case), this returns null. So you can use it to also validate the input.
public static Shift getShiftByName(String name) {
for(Shift s:values()) {
if(s.name().equalsIgnoreCase(name)) {
return s;
}
}
return null;
}
//if you want to convert it back to a String (for output), overwrite toString:
#Override
public String toString() {
//name() returns the constant's name as a String, such as "MORNING".
// since you use it as lowercase, overriding toString here makes sense
return name().toLowerCase();
}
}
You can then use it as
String strShiftInput = "morning";
Shift chosenChift = getShiftByName(strShiftInput);
if(chosenShift == null) {
//invalid input, handle accordingly
}
new PartTimeStaffHire(theOtherParameters, chosenShift);

My DecagonalPrismApp won't print the output

I can't get the output to print, I've tried many diff. things to try and get it to print but it won't work. It's supposed to print error messages if I put in a negative # for height or edge. Also the output for valid #'s won't print either. I'm not sure where to put the block of code for that one. Can someone help me?
My Program: https://pastebin.com/D8FQv1yR
import java.util.Scanner;
/**
*The App for the Decagonal Prism program.
* #author Kathleen Tumlin - Fundamentals of Computing I - 1210
* #version 9/17/21
*/
public class DecagonalPrismApp {
//fields
String label = "";
double edge = 0;
double height = 0;
double edgeIn = 0;
double heightIn = 0;
// constuctor
/** Shows public decagonal prism, setLabel, and setEdge.
* #param labelIn takes input for label in the constructor.
* #param edgeIn takes input for the edge in the constructor.
*/
public DecagonalPrismApp(String labelIn, double edgeIn, double heightIn) {
setLabel(labelIn);
setEdge(edgeIn);
setHeight(heightIn);
}
//methods
/** Shows the return for label variable.
* #return returns the label variable.
*/
public String getLabel() {
return label;
}
/** Shows the set label.
* #param labelIn takes the labelIn for the method.
* #return returns the boolean if the variable was set.
*/
public boolean setLabel(String labelIn) {
if (labelIn != null) {
label = labelIn.trim();
return true;
} else {
return false;
}
}
/** Shows the return for the edge variable.
* #return returns the value for the variable edge.
*/
public double getEdge() {
return edge;
}
/** Shows the set edge.
* #param edgeIn takes the edgein and sets it as the edge variable.
* #return returns the boolean if the variable was set.
*/
public boolean setEdge(double edgeIn) {
if (edgeIn > -1) {
edge = edgeIn;
return true;
}
else {
System.out.println("Error: edge must be non-negative.");
return false;
}
}
/** Shows the return for the height variable.
*#return returns the value for the variable edge.
*/
public double getHeight() {
return height;
}
/** Shows the set height.
* #param heightIn takes the heightin and sets it as the height variable.
* #return returns the boolean if the variable was set.
*/
public boolean setHeight(double heightIn) {
if (heightIn > -1) {
height = heightIn;
return true;
}
else {
System.out.println("Error: height must be non-negative.");
return false;
}
}
public void start() {
do {
System.out.print("Error: height must be non-negative." );
} while (heightIn > -1);
do {
System.out.print("Error: edge must be non-negative." );
} while (edgeIn > -1);
}
public static void main(String[] args) {
/**
*Shows what prints.
* #param args not used.
*/
Scanner scan = new Scanner(System.in);
System.out.println("Enter label, edge, and height length for a "
+ "decagonal prism.");
System.out.print("\tlabel: ");
String label = scan.nextLine();
System.out.print("\tedge: ");
double edge = scan.nextDouble();
System.out.print("\theight: ");
double height = scan.nextDouble();
}
}
Valid #'s code: https://pastebin.com/DPuSpMEq
public String toString() {
DecimalFormat fmt = new DecimalFormat("#,##0.0##");
return "A decagonal prism \"" + label
+ "with edge = " + edge + " units.\n\t"
+ "and height = " + height + " units.\n\t has:"
+ "surface area = " + fmt.format(surfaceArea()) + " square units\n\t"
+ "base area = " + fmt.format(baseArea()) + " square units \n\t"
+ "lateral surface area = "
+ fmt.format(lateralSurfaceArea()) + " square units\n\t"
+ "volume = " + fmt.format(volume()) + " cubic units \n\t";

How to use toString and getter and setter methods

I'm riding the struggle bus with the below instructions. I can't figure out how to use the toString() method to print my data values. I also don't know how to get the color to print as a string to say "Black" or "Blue". And I can't figure out how to use the boolean value to say "connected" or "disconnected".
Create a Java class named HeadPhone to represent a headphone set. The class contains:
• Three constants named LOW, MEDIUM and HIGH with values of 1, 2 and 3
to denote the headphone volume.
• A private int data field named volume that specifies the volume of
the headphone. The default volume is MEDIUM.
• A private boolean data field named pluggedIn that specifies if the
headphone is plugged in. The default value if false.
• A private String data field named manufacturer that specifies the
name of the manufacturer of the headphones.
• A private Color data field named headPhoneColor that specifies the
color of the headphones.
• getter and setter methods for all data fields.
• A no argument constructor that creates a default headphone.
• A method named toString() that returns a string describing the
current field values of the headphones.
• A method named changeVolume(value) that changes the volume of the
headphone to the value passed into the method
Create a TestHeadPhone class that constructs at least 3 HeadPhone
objects.
public class TestHeadPhone {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// construct an object
HeadPhone headPhone = new HeadPhone();
System.out.println("Manufacturer: " + headPhone.getManufacturer());
System.out.println("Color: " + headPhone.getColor());
System.out.println("Currently: " + headPhone.getStatus());
System.out.println("Volume: " + headPhone.getVolume());
if(headPhone.getStatus() == false){
System.out.println("Please plug the Head Phones into a device.");
}
headPhone.setNewHeadphone();
System.out.println("\n" + "Manufacturer: " +
headPhone.getManufacturer());
System.out.println("Color: " + headPhone.getColor());
System.out.println("Currently: " + headPhone.getStatus());
System.out.println("Volume: " + headPhone.getVolume());
if(headPhone.getStatus() == true){
System.out.println("Currently playing classical music.");
}
}
}
package testheadphone;
// import color class
import java.awt.Color;
/**
*
* #author
*/
public class HeadPhone {
// class variables
private static final int LOW = 1;
private static final int MEDIUM = 2;
private static final int HIGH = 3;
private int volume = MEDIUM;
private boolean pluggedIn = false;
private String manufacturer;
private Color headPhoneColor;
//default constructor method
public HeadPhone(){
this.manufacturer = "Bose";
this.headPhoneColor = Color.black;
this.volume = MEDIUM;
this.pluggedIn = false;
} // end default constructor
// getter method
public String getManufacturer(){
return manufacturer;
}
// getter method
public Color getColor(){
return headPhoneColor;
}
// getter method
public int getVolume(){
return volume;
}
// getter method
public boolean getStatus(){
return pluggedIn;
}
public int changeVolume(int change){
volume = change;
return volume;
}
// setter method
public void setNewHeadphone(){
manufacturer = "JVC";
headPhoneColor = Color.blue;
pluggedIn = true;
volume = HIGH;
}
// #Override
// public String toString(){
// return "Head Phone 1 has the folllowing parameters: " + "\n" +
// "Manufacturer: " + this.manufacturer + "\n" + "Color: Black" +
// "\n" + "Volume is set to: " + this.volume + "\n" +
// "Currently: disconnected" + "\n" + "Please plug the Head Phone"
// + " into a device";
// }
}
My Output:
Manufacturer: Bose
Color: java.awt.Color[r=0, g=0, b=0]
Currently: false
Volume: 2
Please plug the Head Phones into a device.
Manufacturer: JVC
Color: java.awt.Color[r=0,g=0,b=255]
Currently: true
Volume: 3
Currently playing classical music.
Required output:
Manufacturer: Bose
Color: Black
Currently: disconnected
Volume is set to: MEDIUM
Please plug the Head Phones into a device.
Head Phone 2 has the following parameters:
Manufacturer: JVC
Color: Blue
Currently: connected
Volume is set to: LOW
Currently playing classical music playlist
You can override the toString() methods of the objects you want to print. However some objects already have their toString() methods implemented for you with a human-readable format. i.e. the Color class.
...
System.out.println("Color: " + headPhone.getColor().toString());
...
On the other hand, you have the freedom to specify what format the object shall be displayed as a String by overriding. (Unless there are class restrictions on what can/cannot be modified, i.e. the final keyword.)
If overriding the toString() methods end up being not possible for your project, you can always just explicitly format the display string conditionally using their primitive values. i.e.
System.out.println("Currently: " + (headPhone.getStatus() ? "connected" : "disconnected"));
...
Be aware of the issue that you will need to do this each time you want to print out the status in other parts of the code. overriding the toString() does it everywhere, uniformly.
Have a look at this code. It may help.
public class TestHeadPhones {
/**
* #param args
*/
public static void main(String[] args) {
HeadPhones h1 = new HeadPhones();
h1.setVolume(2);
h1.setHeadPhoneColor("CYAN");
h1.setManufacturer("Bass");
h1.setPluggedIn(true);
HeadPhones h2 = new HeadPhones();
h2.setVolume(1);
h2.setHeadPhoneColor("blue");
h2.setManufacturer("Bass");
h2.setPluggedIn(true);
HeadPhones h3 = new HeadPhones();
h3.setVolume(HeadPhones.HIGH);
h3.setHeadPhoneColor("DARK GRAY");
h3.setManufacturer("Bass");
h3.setPluggedIn(true);
// Print description of all headphones
System.out.println("Description of Headphone 1");
System.out.println(h1.toString() + "\n");
System.out.println("Description of Headphone 2");
System.out.println(h2.toString() + "\n");
System.out.println("Description of Headphone 3");
System.out.println(h3.toString() + "\n");
//change volume of headphone 1
h1.changeVolume(3);
System.out.println("Description of Headphone 1");
System.out.println(h1.toString() + "\n");
}
}
Here is the HeadPhones class
public class HeadPhones {
public static final int LOW = 1;
public static final int MEDIUM = 2;
public static final int HIGH = 3;
private int volume = MEDIUM;
private boolean pluggedIn = false;
private String manufacturer;
private String headPhoneColor;
/**
* Default Constructor
*/
public HeadPhones() {
}
/***
* Change the voulme
* #param value
*/
public void changeVolume(int value) {
setVolume(value);
}
/**
* Return Description of Object
*/
public String toString() {
return "Volume: " + getVolume() + "\n" + "Plugin is set: "
+ isPluggedIn() + "\n" + "Color of HeadePhone: "
+ getHeadPhoneColor() + "\n" + "Manufacturer: "
+ getManufacturer();
}
/**
* Set volume
* #param volume
*/
public void setVolume(int volume) {
this.volume = volume;
}
/***
* Get Volume
* #return volume
*/
public int getVolume() {
return volume;
}
/**
* Set plugin
* #param pluggedIn
*/
public void setPluggedIn(boolean pluggedIn) {
this.pluggedIn = pluggedIn;
}
/***
* Get Plugin is true or false
* #return pluggedIn
*/
public boolean isPluggedIn() {
return pluggedIn;
}
/***
* Set Manufacture
* #param manufacturer
*/
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
/***
* Get Manufacture
* #return manufacturer
*/
public String getManufacturer() {
return manufacturer;
}
/***
* Set the Color
* #param headPhoneColor
*/
public void setHeadPhoneColor(String headPhoneColor) {
this.headPhoneColor = headPhoneColor;
}
/**
* This method will return the color
* #return headPhoneColor
*/
public String getHeadPhoneColor() {
return headPhoneColor;
}
}

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.

Why doesn't this variable change when I set it

I have a method called setLevel
/**
* Sets the level of this course.
*
* #param newLevel - one of the enumerated levels
*/
public void setLevel(char newLevel)
{
if(newLevel == 7 || newLevel == 1 || newLevel == 9 || newLevel == 8)
{
level = newLevel;
}
else
{
level = DEFAULT_LEVEL;
}
} // end of method setLevel(char newLevel)
when I use this method, I set the Level
I have another method called getLevel
/**
* Returns the level of this course.
*
* #return the level of this course
*/
public char getLevel()
{
return level;
} // end of method getLevel()
but when I call this method, it displays a default level that I have set.
Any ideas as to how to fix it
Here is the full code
public class Course extends Object implements Serializable
{
// instance variables
private int academicYear;
private String code;
private static int counter = 0;
private char level;
private String name;
private int serialNumber;
// class constants
private static final String DATA_FILE = "courses.data";
public static final String DEFAULT_CODE = "Introduction to Computer Science";
public static final char DEFAULT_LEVEL = 7;
public static final String DEFAULT_NAME = "ICS3U";
public static final int DEFAULT_YEAR = 2014;
private static final int ERROR_CLASS_NOT_FOUND_EXCEPTION = -1;
private static final int ERROR_EOF_EXCEPTION = -2;
private static final int ERROR_IO_EXCEPTION = -3;
final char[] LEVEL = {'7', '1', '9', '8'};
/**
* Constructor for objects of class Course
*/
public Course()
{
name = DEFAULT_NAME;
code = DEFAULT_CODE;
level = DEFAULT_LEVEL;
academicYear = DEFAULT_YEAR;
serialNumber = ++counter;
} // end of constructor Course()
public Course(String name, String code, char level, int academicYear)
{
this.name = name;
this.code = code;
if (level == 7 || level == 1 || level == 9 || level == 8)
{
level = level;
}
else
{
level = DEFAULT_LEVEL;
}
if (academicYear > 1900 && academicYear < 2014)
{
this.academicYear = academicYear;
}
else
{
academicYear = DEFAULT_YEAR;
}
} // end of constructor Course(String name, String code, char level, int academicYear)
/**
* Indicates whether another object has a state identical to this object’s state.
*
* #param otherCourse - the object whose state is compared to this object’s
*/
public boolean equals(Object otherCourse)
{
if (otherCourse == null) return false;
if (this.getClass() != otherCourse.getClass()) return false;
if (this == otherCourse) return true;
if(this != otherCourse) return false;
// needed to satisfy the compiler
return true;
} // end of method boolean equals(Object course)
/**
* Compares this Course to another.
*/
public int compareTo(Course otherCourse)
{
int before = -1;
int after = 1;
int equals = 0;
int resultCode = code.compareTo(otherCourse.getCode());
if(otherCourse == null) return before ;
if(serialNumber < otherCourse.getSerialNumber()) return before;
if(serialNumber > otherCourse.getSerialNumber()) return after;
if(code.compareTo(otherCourse.getCode()) != 0) return resultCode;
if(!(sortLevel(level) == -1 || sortLevel(otherCourse.getLevel()) == -1))
{
if(sortLevel(level) < sortLevel(otherCourse.getLevel())) return -1;
if(sortLevel(level) > sortLevel(otherCourse.getLevel())) return 1;
}
return 1;
}
private static int sortLevel(char level)
{
final char[] LEVEL = {'7', '1', '9', '8'};
for (int index = 0; index < LEVEL.length; index++)
{
if(LEVEL[index] == level) return index;
if(LEVEL[index] == level) return DEFAULT_LEVEL;
}
// error code for not found, should not be reached
return -1;
}
/* accessors*/
/**
* Returns the code of this course.
*
* #returns Returns the code of this course
*/
public String getCode()
{
return code;
} // end of method getCode()
/**
* Returns the level of this course.
*
* #return the level of this course
*/
public char getLevel()
{
return level;
} // end of method getLevel()
/**
* Returns the name of this course.
*
* #return the name of this course.
*/
public String getName()
{
return name;
} // end of method getName()
/**
* Returns the unique serial number of this course.
*
* #return the unique serial number of this course.
*/
public int getSerialNumber()
{
return serialNumber;
} // end of method getSerialNumber()
/**
* Returns the academic year of this course.
*
* #return the 4-digit academic year of this course
*/
public int getYear()
{
return academicYear;
} // end of method getYear()
/* mutators */
/**
* Sets the code of this course.
*
* #param newCode - the new code of this course.
*/
public void setCode(String newCode)
{
this.code = newCode;
} // end of method setCode(String newCode)
/**
* Sets the level of this course.
*
* #param newLevel - one of the enumerated levels
*/
public void setLevel(char newLevel)
{
if(newLevel == 7 || newLevel == 1 || newLevel == 9 || newLevel == 8)
{
level = newLevel;
}
else
{
level = DEFAULT_LEVEL;
}
} // end of method setLevel(char newLevel)
/**
* Sets the name of this course.
*
* #param newName - the new name of this course
*/
public void setName(String newName)
{
this.name = newName;
} // end of method setName(String newName)
/**
* Sets the academic year of this course.
*
* #param newYear - the new 4-digit academic year of this course
*/
public void setYear(int newYear)
{
if (newYear >= 1900 && newYear <= 2014)
{
this.academicYear = newYear;
}
else
{
academicYear = DEFAULT_YEAR;
}
} // end of method setYear(int newYear)
/**
* Returns a string representation of this course.
*
* #override toString in class Object
*
* #return a string representation of this course.
*/
public String toString()
{
return
this.getClass().getName()
+"["
+ "Serial Number: " + serialNumber
+ ", name: " + name
+ ", code: " + code
+ ", level: " + level
+ ", academic year: " + academicYear
+"]";
} // end of String toString()
} // end of class Course
You have initialised LEVEL with character values '7', '1', '9', '8' but your setLevel method is comparing them with the integer values 7, 1, 9, 8.
They are not the same thing.
Frankly, if LEVEL values are integers then you should declare them as int. You're not achieving anything by storing it as a char.
When you are comparing the newLevel with values.
You are actually comparing ASCII value of newLevel with integers.
This is why every time it is giving Default_level as answer.
use single quotes to compare eg. '7'.
I think you should add single quote while comparing char values
public void setLevel(char newLevel)
{
if(newLevel == '7' || newLevel == '1' || newLevel == '9' || newLevel == '8')
{
level = newLevel;
}
else
{
level = DEFAULT_LEVEL;
}
}

Categories