My DecagonalPrismApp won't print the output - java

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

Related

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.

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.

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

No main class found,

This is a beginners question, why do I get a message about I don't have any main class. I am a total beginner and i have tried to read all the other answers regarding this problem. Im working in netbeans.
/**
* #author Anders
*/
public class Main {
public enum Valuta { // here i assign the values i allow from the argument
EUR,
USD,
RUB;
// here i assign the conversionrates
static final float C_EUR_TO_DKK_RATE = (float) 7.44;
static final float C_USD_TO_DKK_RATE = (float) 5.11;
static final float C_RUB_TO_DKK_RATE = (float) 0.156;
static float result = 0;
static int value = 0;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
if (args.length == 2) {
value = Integer.parseInt(args[0]);
String valutaIn = args[1]; //equalsIgnoreCase(null) boolean expression. How does this works??
Valuta enumConvert = Valuta.valueOf(valutaIn);
switch (enumConvert) {
case EUR:
result = value * C_EUR_TO_DKK_RATE;
break;
case USD:
result = value * C_USD_TO_DKK_RATE;
break;
case RUB:
result = value * C_RUB_TO_DKK_RATE;
break;
}
System.out.println((float) value + "" + enumConvert + " converts to " + (result * 100.) / 100.0 + "Dk");
}
else {
System.exit(1);
}
}
}
}
The method main is not in the Class Main, it is inside the enum Valuta. You probably intended the following (note the closing curly bracket after the enum):
/**
* #author Anders
*/
public class Main {
public enum Valuta { // here i assign the values i allow from the argument
EUR,
USD,
RUB;
}
// here i assign the conversionrates
static final float C_EUR_TO_DKK_RATE = (float) 7.44;
static final float C_USD_TO_DKK_RATE = (float) 5.11;
static final float C_RUB_TO_DKK_RATE = (float) 0.156;
static float result = 0;
static int value = 0;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
if (args.length == 2) {
value = Integer.parseInt(args[0]);
String valutaIn = args[1]; //equalsIgnoreCase(null) boolean expression. How does this works??
Valuta enumConvert = Valuta.valueOf(valutaIn);
switch (enumConvert) {
case EUR:
result = value * C_EUR_TO_DKK_RATE;
break;
case USD:
result = value * C_USD_TO_DKK_RATE;
break;
case RUB:
result = value * C_RUB_TO_DKK_RATE;
break;
}
System.out.println((float) value + "" + enumConvert + " converts to " + (result * 100.) / 100.0 + "Dk");
}
else {
System.exit(1);
}
}
}

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;

Categories