How to use toString and getter and setter methods - java

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;
}
}

Related

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";

Can't call a method, trying to get a variable from one method to another

I am stuck trying to call a method. No matter what I do, I get an error that it can't find the symbol. I am trying to use the variables total (from the surfaceArea method) and volume (from the volume method).
The problems are in the toString method, where it cannot see the variables no matter what I do. I am sure it is something incredibly basic I a missing, so I hope someone can figure it out.
Here is the Error Log:
Ellipsoid.java:176: error: cannot find symbol
String vout = df.format(volume);
^
symbol: variable volume
location: class Ellipsoid
Ellipsoid.java:177: error: cannot find symbol
String sout = df.format(total);
^
symbol: variable total
location: class Ellipsoid
2 errors
And here is the code itself. I tried to make it as easy to read as possible:
/**
* This program lets the user enter values of and Ellipsoid.
* #version 02/05/2020
*/
public class Ellipsoid {
// fields
private String label;
private double a, b, c;
//public double total, volume;
// constructor
/**
* This constructor creates a ellipsoid and gets its information.
*
* #param labelIn is the label entered by the user.
* #param aIn is the a valuve entered by the user.
* #param bIn is the b valuve entered by the user.
* #param cIn is the c valuve entered by the user.
*/
public Ellipsoid(String labelIn, double aIn, double bIn, double cIn) {
setLabel(labelIn);
setA(aIn);
setB(bIn);
setC(cIn);
}
// methods
/**
* This method gets the label string.
* #return returns the label of the ellipsoid.
*/
public String getLabel() {
return label;
}
/**
* This method sets the label of the ellipsoid.
* #param labelIn is the label entered by the user.
* #return returns true or false depending on user input.
*/
public boolean setLabel(String labelIn) {
if (labelIn == null) {
return false;
}
else {
label = labelIn.trim();
return true;
}
}
/**
* This method gets the a values of the ellipsoid.
* #return returns a values of the ellipsoid.
*/
public double getA() {
return a;
}
/**
* This method sets the a value of the ellipsoid.
* #param aIn is the a value entered by the user.
* #return returns true or false depending on the user input.
*/
public boolean setA(double aIn)
{
if (aIn > 0)
{
a = aIn;
return true;
}
else
{
return false;
}
}
/**
* This method gets the b value of the ellipsoid.
* #return returns the b value of the ellipsoid.
*/
public double getB()
{
return b;
}
/**
* This method sets the b value of the ellipsoid.
* #param bIn is the b value entered by the user.
* #return returns true or false depending on the user input.
*/
public boolean setB(double bIn)
{
if (bIn > 0)
{
b = bIn;
return true;
}
else
{
return false;
}
}
/**
* This method gets the c value of the ellipsoid.
* #return returns the c value of the ellipsoid.
*/
public double getC()
{
return c;
}
/**
* This method sets the c value of the ellipsoid.
* #param cIn is the c value entered by the user.
* #return returns true or false depending on the user input.
*/
public boolean setC(double cIn)
{
if (cIn > 0)
{
c = cIn;
return true;
}
else
{
return false;
}
}
/**
* This method finds the volume of the ellipsoid.
* #return returns the volume of the ellipsoid.
*/
public double volume()
{
double volume = 4 * Math.PI * a * b * c;
volume = volume / 3;
return volume;
}
/**
* This method finds the surface area of the ellipsoid.
* #return returns the surface area.
*/
public double surfaceArea() {
double ab = (a * b);
ab = Math.pow(ab, 1.6);
double ac = a * c;
ac = Math.pow(ac, 1.6);
double bc = b * c;
bc = Math.pow(bc, 1.6);
double top = ab + ac + bc;
double bottom = top / 3;
double full = bottom * 1 / 1.6;
double total = 4 * Math.PI * full;
return total;
}
/**
* This method prints the information of the ellipsoid.
* #return returns the information of the ellipsoid.
*/
public String toString() {
DecimalFormat df = new DecimalFormat("#,##0.0###");
surfaceArea();
volume();
String aout = df.format(a);
String bout = df.format(b);
String cout = df.format(c);
String vout = df.format(volume);
String sout = df.format(total);
String output = "Ellipsoid \"" + label + "\" with axes a = " + aout
+ ", b = " + bout + ", c = " + cout + " units has:\n\tvolume = "
+ vout + " cubic units\n\tsurface area = "
+ sout + " square units";
return output;
}
}
volume and total are local members to volume() and surfaceArea() methods respectively. It is not visible in toString() method. But a, b and c are visible as they are declared class level. Try assigning returned values from those methods to local variables in toString() as below:
public String toString() {
DecimalFormat df = new DecimalFormat("#,##0.0###");
double total = surfaceArea();
double volume = volume();
....
String vout = df.format(volume);
String sout = df.format(total);
....
}
In the Ellipsoid class, you didn't declare the total and volume variables.
They are commented there, try to uncomment this line:
//public double total, volume;
Should help, but if you want to assign the values to those instance fields while calculating, change the double total and double total in the proper methods to this.total and this.volume.
This will allow you to both keep the data inside object and return it through method.

Why is this an unreachable statement? 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.

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;

toString() and accessors

public class Fan {
public static void main(String[] args){
Fan fan1 = new Fan();
fan1.setSpeed(FAST);
fan1.setRadius(10);
fan1.setColor("yellow");
fan1.setOn(true);
System.out.println(fan1.toString());
}
// fan speed variables
final static int SLOW = 1;
final static int MEDIUM = 2;
final static int FAST = 3;
// Other fan variables
private int speed;
private boolean on; // true means on
private double radius; // radius of fan
String color;
// No-arg constructor
public void Fan(){
speed = SLOW;
on = false;
radius = 5;
color = "blue";
}
// Mutator methods
public void setSpeed(int newSpeed){
if(newSpeed < 0)
System.out.println("Illegal speed!");
else
speed = newSpeed;
}
public void setOn(boolean newOn){
on = newOn;
}
public void setRadius(int newRadius){
if(newRadius < 0)
System.out.println("Illegal radius!");
else
radius = newRadius;
}
public void setColor(String newColor){
color = newColor;
}
// Accessor methods
public int getSpeed(){
return speed;
}
public boolean getOn(){
return on;
}
public double getRadius(){
return radius;
}
public String getColor(){
return color;
}
// toString method to output Fan data
public String toString(){
if(on = false)
return "Fan is off.";
else
return "Fan Properties:\n" + "Fan speed: " + speed + "\n"
+ "Color: " + color + "\n"
+ "Radius: " + radius + "\n";
}
}
The above piece of code is simple but I was wondering how the toString method uses the on variable even though I didn't supply parameters for that method. Also, why do we not need to invoke get methods in the main class and only need to invoke the set methods? (please explain how each method invokes one another until the final output)
Thanks a lot!
As far as you are in this class body you can access everything (except for static can not access non-static). That means that you can easily set and get variables like that:
var = <value>;
System.out.println(var);
However nobody stops you from using the accessor methods - getter and setters. It is just not required.
One final note:
if(on = false)
This will always fail - it does assignment to false and then checks the newly assigned value (which is false). You need to check for equality here. Like that:
if(on == false)
Or even better:
if(!on)
I just copied-pasted your code into a new file and compiled it. It compiled and ran. The output was
$ java Fan
Fan Properties:
Fan speed: 3
Color: yellow
Radius: 10.0
This is because the comparison in your toString method is wrong. It should be as following:
public String toString(){
if(on)
return "Fan Properties:\n" + "Fan speed: " + speed + "\n"
+ "Color: " + color + "\n"
+ "Radius: " + radius + "\n";
else
return "Fan is off.";
}

Categories