This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I am trying to create a program where you can change a fans speed, color, radius, and whether you can turn the fan on or off, I have the fan class working fine, except for the toString() method, for some reason when I set some values in the test program, it just defaults to the regular values, any help is accepted.
Thank you.
public class Fan {
final int SLOW = 1;
final int MEDIUM = 2;
final int FAST = 3;
public int speed = SLOW;
public boolean on = false;
public double radius = 5;
public String color = new String("blue");
//fan on
boolean fanOn() {
on = true;
return on;
}
//fan off
boolean fanOff() {
on = false;
return on;
}
//sets fan speed
String setSpeed(String speed) {
if (speed == "SLOW"){
speed = String.valueOf(SLOW);
} else if (speed == "MEDIUM") {
speed = String.valueOf(MEDIUM);
} else if (speed == "FAST") {
speed = String.valueOf(FAST);
} else {
speed = "Please enter 'SLOW', 'MEDIUM' or 'FAST' to change the speed of the fan.";
}
return speed;
}
//sets custom radius
double setRadius(double rad) {
rad = radius;
return rad;
}
//sets custom color
String setColor(String colorType) {
return colorType;
}
//toString() method
public String toString() {
return ("Speed: " + speed + "\nRadius: " + radius + "\nColor: " + "\nOn: " + on);
}
}
//test program
public class TestFan {
public static void main(String[] args) {
Fan fan1 = new Fan();
fan1.setColor("green");
fan1.setSpeed("FAST");
fan1.setRadius(3.5);
fan1.fanOff();
System.out.println(fan1.toString());
}
}
This just outputs:
Speed: 1
Radius: 5.0
Color:
On: false
public class Fan {
final int SLOW = 1;
final int MEDIUM = 2;
final int FAST = 3;
public int speed = SLOW;
public boolean on = false;
public double radius = 5;
public String color = new String("blue");
//fan on
void fanOn() {
on = true;
return on;
}
//fan off
void fanOff() {
on = false;
return on;
}
//sets fan speed
void setSpeed(String speed) {
this.speed=speed;
}
//sets custom radius
double setRadius(double rad) {
rad = radius;
return rad;
}
//sets custom color
void setColor(String colorType) {
color = colorType;
}
//toString() method
public String toString() {
return ("Speed: " + speed + "\nRadius: " + radius + "\nColor: " + "\nOn: " + on);
}
}
//test program
public class TestFan {
public static void main(String[] args) {
Fan fan1 = new Fan();
fan1.setColor("green");
fan1.setSpeed("FAST");
fan1.setRadius(3.5);
fan1.fanOff();
System.out.println(fan1.toString());
}
}
Related
I am programming a very basic bot for planet wars in java and I cant seem to find the errors in my code. I am receiving a few different error messages but the main issue for me is the error: class, interface, or enum expected. Ive checked my brackets about a thousand times. Any help would be appreciated. Here's my bot code:
import java.util.List;
import java.util.Random;
import shared.Planet;
import shared.PlanetWars;
public class MyNewBot {
public static void doTurn(PlanetWars pw) {
// (1) If we currently have a fleet in flight, then do nothing until
// it arrives.
if (pw.myFleets().size() >= 10) {
return;
}
// (2) Pick one of my planets based on the number of ships
Planet source = null;
int largestForce = 0;
for (Planet p : pw.myPlanets()){
int force = pw.numShips();
if( force > largestForce){
largestForce = force;
source = p;
}
}
// (3) Pick a target planet at random.
Planet dest = null;
int highestGrowthRate = 0;
int shortestDistance = 9999;
for (Planet p = pw.notMyPlanets()){
int growthRate = pw.growthRate();
if( growthRate > highestGrowthRate){
highestGrowthRate = growthRate;
dest = p;
}else if (growthRate == highestGrowthRate){
int distance = pw.distance(source,p);
if (distance < shortestDistance){
shortestDistance = distance;
dest = p;
}
}
}
// (4) Send half the ships from source to destination.
if (source != null && dest != null) {
int numShips = source.numShips() / 2;
pw.issueOrder(source, dest, numShips);
}
}
// Ignore the main method unless you know what you're doing.
// Refer to the doTurn function to code your bot.
public static void main(String[] args) {
String line = "";
String message = "";
int c;
try {
while ((c = System.in.read()) >= 0) {
switch (c) {
case '\n':
if (line.equals("go")) {
PlanetWars pw = new PlanetWars(message);
doTurn(pw);
pw.finishTurn();
message = "";
} else {
message += line + "\n";
}
line = "";
break;
default:
line += (char) c;
break;
}
}
} catch (Exception e) {
// Owned.
}
}
}
and the supporting class files:
package shared;
public class Planet implements Cloneable {
private int planetID;
private int owner;
private int numShips;
private int growthRate;
private double x, y;
public Planet(int planetID, int owner, int numShips, int growthRate,
double x, double y) {
this.planetID = planetID;
this.owner = owner;
this.numShips = numShips;
this.growthRate = growthRate;
this.x = x;
this.y = y;
}
public int planetID() {
return planetID;
}
public int owner() {
return owner;
}
public int numShips() {
return numShips;
}
public int growthRate() {
return growthRate;
}
public double x() {
return x;
}
public double y() {
return y;
}
public void owner(int newOwner) {
this.owner = newOwner;
}
public void numShips(int newNumShips) {
this.numShips = newNumShips;
}
public void addShips(int amount) {
numShips += amount;
}
public void removeShips(int amount) {
numShips -= amount;
}
private Planet(Planet _p) {
planetID = _p.planetID;
owner = _p.owner;
numShips = _p.numShips;
growthRate = _p.growthRate;
x = _p.x;
y = _p.y;
}
public Object clone() {
return new Planet(this);
}
}
package shared;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class PlanetWars {
// Constructs a PlanetWars object instance, given a string containing a
// description of a game state.
public PlanetWars(String gameStateString) {
planets = new ArrayList<Planet>();
fleets = new ArrayList<Fleet>();
parseGameState(gameStateString);
}
// Returns the number of planets. Planets are numbered starting with 0.
public int numPlanets() {
return planets.size();
}
// Returns the planet with the given planet_id. There are NumPlanets()
// planets. They are numbered starting at 0.
public Planet getPlanet(int planetID) {
return planets.get(planetID);
}
// Returns the number of fleets.
public int numFleets() {
return fleets.size();
}
// Returns the fleet with the given fleet_id. Fleets are numbered starting
// with 0. There are NumFleets() fleets. fleet_id's are not consistent from
// one turn to the next.
public Fleet getFleet(int fleetID) {
return fleets.get(fleetID);
}
// Returns a list of all the planets.
public List<Planet> planets() {
return planets;
}
// Return a list of all the planets owned by the current player. By
// convention, the current player is always player number 1.
public List<Planet> myPlanets() {
List<Planet> r = new ArrayList<Planet>();
for (Planet p : planets) {
if (p.owner() == 1) {
r.add(p);
}
}
return r;
}
// Return a list of all neutral planets.
public List<Planet> neutralPlanets() {
List<Planet> r = new ArrayList<Planet>();
for (Planet p : planets) {
if (p.owner() == 0) {
r.add(p);
}
}
return r;
}
// Return a list of all the planets owned by rival players. This excludes
// planets owned by the current player, as well as neutral planets.
public List<Planet> enemyPlanets() {
List<Planet> r = new ArrayList<Planet>();
for (Planet p : planets) {
if (p.owner() >= 2) {
r.add(p);
}
}
return r;
}
// Return a list of all the planets that are not owned by the current
// player. This includes all enemy planets and neutral planets.
public List<Planet> notMyPlanets() {
List<Planet> r = new ArrayList<Planet>();
for (Planet p : planets) {
if (p.owner() != 1) {
r.add(p);
}
}
return r;
}
// Return a list of all the fleets.
public List<Fleet> fleets() {
List<Fleet> r = new ArrayList<Fleet>();
for (Fleet f : fleets) {
r.add(f);
}
return r;
}
// Return a list of all the fleets owned by the current player.
public List<Fleet> myFleets() {
List<Fleet> r = new ArrayList<Fleet>();
for (Fleet f : fleets) {
if (f.owner() == 1) {
r.add(f);
}
}
return r;
}
// Return a list of all the fleets owned by enemy players.
public List<Fleet> enemyFleets() {
List<Fleet> r = new ArrayList<Fleet>();
for (Fleet f : fleets) {
if (f.owner() != 1) {
r.add(f);
}
}
return r;
}
// Returns the distance between two planets, rounded up to the next highest
// integer. This is the number of discrete time steps it takes to get
// between the two planets.
public int distance(int sourcePlanet, int destinationPlanet) {
Planet source = planets.get(sourcePlanet);
Planet destination = planets.get(destinationPlanet);
double dx = source.x() - destination.x();
double dy = source.y() - destination.y();
return (int) Math.ceil(Math.sqrt(dx * dx + dy * dy));
}
// Returns the distance between two planets, rounded up to the next highest
// integer. This is the number of discrete time steps it takes to get
// between the two planets.
public int distance(Planet source, Planet destination) {
double dx = source.x() - destination.x();
double dy = source.y() - destination.y();
return (int) Math.ceil(Math.sqrt(dx * dx + dy * dy));
}
// Sends an order to the game engine. An order is composed of a source
// planet number, a destination planet number, and a number of ships. A
// few things to keep in mind:
// * you can issue many orders per turn if you like.
// * the planets are numbered starting at zero, not one.
// * you must own the source planet. If you break this rule, the game
// engine kicks your bot out of the game instantly.
// * you can't move more ships than are currently on the source planet.
// * the ships will take a few turns to reach their destination. Travel
// is not instant. See the Distance() function for more info.
public void issueOrder(int sourcePlanet, int destinationPlanet, int
numShips) {
System.out.println("" + sourcePlanet + " " + destinationPlanet + " "
+ numShips);
System.out.flush();
}
// Sends an order to the game engine. An order is composed of a source
// planet number, a destination planet number, and a number of ships. A
// few things to keep in mind:
// * you can issue many orders per turn if you like.
// * the planets are numbered starting at zero, not one.
// * you must own the source planet. If you break this rule, the game
// engine kicks your bot out of the game instantly.
// * you can't move more ships than are currently on the source planet.
// * the ships will take a few turns to reach their destination. Travel
// is not instant. See the Distance() function for more info.
public void issueOrder(Planet source, Planet dest, int numShips) {
System.out.println("" + source.planetID() + " " + dest.planetID() + " "
+ numShips);
System.out.flush();
}
// Sends the game engine a message to let it know that we're done sending
// orders. This signifies the end of our turn.
public void finishTurn() {
System.out.println("go");
System.out.flush();
}
// Returns true if the named player owns at least one planet or fleet.
// Otherwise, the player is deemed to be dead and false is returned.
public boolean isAlive(int playerID) {
for (Planet p : planets) {
if (p.owner() == playerID) {
return true;
}
}
for (Fleet f : fleets) {
if (f.owner() == playerID) {
return true;
}
}
return false;
}
// If the game is not yet over (ie: at least two players have planets or
// fleets remaining), returns -1. If the game is over (ie: only one player
// is left) then that player's number is returned. If there are no
// remaining players, then the game is a draw and 0 is returned.
public int winner() {
Set<Integer> remainingPlayers = new TreeSet<Integer>();
for (Planet p : planets) {
remainingPlayers.add(p.owner());
}
for (Fleet f : fleets) {
remainingPlayers.add(f.owner());
}
switch (remainingPlayers.size()) {
case 0:
return 0;
case 1:
return ((Integer) remainingPlayers.toArray()[0]).intValue();
default:
return -1;
}
}
// Returns the number of ships that the current player has, either located
// on planets or in flight.
public int numShips(int playerID) {
int numShips = 0;
for (Planet p : planets) {
if (p.owner() == playerID) {
numShips += p.numShips();
}
}
for (Fleet f : fleets) {
if (f.owner() == playerID) {
numShips += f.numShips();
}
}
return numShips;
}
// Returns the production of the given player.
public int production(int playerID) {
int prod = 0;
for (Planet p : planets) {
if (p.owner() == playerID) {
prod += p.growthRate();
}
}
return prod;
}
// Parses a game state from a string. On success, returns 1. On failure,
// returns 0.
private int parseGameState(String s) {
planets.clear();
fleets.clear();
int planetID = 0;
String[] lines = s.split("\n");
for (int i = 0; i < lines.length; ++i) {
String line = lines[i];
int commentBegin = line.indexOf('#');
if (commentBegin >= 0) {
line = line.substring(0, commentBegin);
}
if (line.trim().length() == 0) {
continue;
}
String[] tokens = line.split(" ");
if (tokens.length == 0) {
continue;
}
if (tokens[0].equals("P")) {
if (tokens.length != 6) {
return 0;
}
double x = Double.parseDouble(tokens[1]);
double y = Double.parseDouble(tokens[2]);
int owner = Integer.parseInt(tokens[3]);
int numShips = Integer.parseInt(tokens[4]);
int growthRate = Integer.parseInt(tokens[5]);
Planet p = new Planet(planetID++, owner, numShips, growthRate,
x, y);
planets.add(p);
} else if (tokens[0].equals("F")) {
if (tokens.length != 7) {
return 0;
}
int owner = Integer.parseInt(tokens[1]);
int numShips = Integer.parseInt(tokens[2]);
int source = Integer.parseInt(tokens[3]);
int destination = Integer.parseInt(tokens[4]);
int totalTripLength = Integer.parseInt(tokens[5]);
int turnsRemaining = Integer.parseInt(tokens[6]);
Fleet f = new Fleet(owner, numShips, source, destination,
totalTripLength, turnsRemaining);
fleets.add(f);
} else {
return 0;
}
}
return 1;
}
// Store all the planets and fleets. OMG we wouldn't wanna lose all the
// planets and fleets, would we!?
private ArrayList<Planet> planets;
private ArrayList<Fleet> fleets;
}
package shared;
public class Fleet implements Comparable<Fleet>, Cloneable {
private int owner;
private int numShips;
private int sourcePlanet;
private int destinationPlanet;
private int totalTripLength;
private int turnsRemaining;
public Fleet(int owner, int numShips, int sourcePlanet,
int destinationPlanet, int totalTripLength, int turnsRemaining) {
this.owner = owner;
this.numShips = numShips;
this.sourcePlanet = sourcePlanet;
this.destinationPlanet = destinationPlanet;
this.totalTripLength = totalTripLength;
this.turnsRemaining = turnsRemaining;
}
public Fleet(int owner, int numShips) {
this.owner = owner;
this.numShips = numShips;
this.sourcePlanet = -1;
this.destinationPlanet = -1;
this.totalTripLength = -1;
this.turnsRemaining = -1;
}
public int owner() {
return owner;
}
public int numShips() {
return numShips;
}
public int sourcePlanet() {
return sourcePlanet;
}
public int destinationPlanet() {
return destinationPlanet;
}
public int totalTripLength() {
return totalTripLength;
}
public int turnsRemaining() {
return turnsRemaining;
}
public void removeShips(int amount) {
numShips -= amount;
}
// Subtracts one turn remaining. Call this function to make the fleet get
// one turn closer to its destination.
public void TimeStep() {
if (turnsRemaining > 0) {
--turnsRemaining;
} else {
turnsRemaining = 0;
}
}
#Override
public int compareTo(Fleet f) {
return this.numShips - f.numShips;
}
private Fleet(Fleet _f) {
owner = _f.owner;
numShips = _f.numShips;
sourcePlanet = _f.sourcePlanet;
destinationPlanet = _f.destinationPlanet;
totalTripLength = _f.totalTripLength;
turnsRemaining = _f.turnsRemaining;
}
public Object clone() {
return new Fleet(this);
}
}
for (Planet p = pw.notMyPlanets()){ should be for (Planet p : pw.notMyPlanets()){.
You've not posted the Fleet class, so as it is the code won't compile for me. However, the above is the only other error I could see.
All of the program's templates. This was a past assignment but at this point, I'm just trying to understand what's going on.
Under the Apartment class, I'm confused on how to correctly return an array of window orders for one unit, all units, and then the #Override method under ThreeBedroom.
Just for reference of what I've done so far (probably not all correct):
public class Window {
private final int width, height;
public Window(int width, int height) {
this.width = width;
this.height = height;
}
// print text like: 4 X 6 window
public String toString() {
String s = "";
s = width + " x " + height + " window";
return s;
}
// compare window objects by their dimensions
public boolean equals(Object that) {
if (that instanceof Window) {
Window w = (Window) that;
return this.width == w.width && this.height == w.height;
}
else { return false; }
}
}
class WindowOrder {
final Window window; // window description (its width and height)
int num; // number of windows for this order
WindowOrder(Window window, int num) {
this.window = window;
this.num = num;
}
// add the num field of the parameter to the num field of this object
//
// BUT
//
// do the merging only of two windows have the same size
// do nothing if the size does not match
//
// return the current object
WindowOrder add(WindowOrder order) {
if (order.equals(window)) {
this.num -= num;
return order;
}
else {
return order;
}
}
// update the num field of this object by multiplying it with the parameter
// and then return the current object
WindowOrder times(int number) {
WindowOrder window = new WindowOrder(this.window, this.num);
this.num *= number;
return window;
}
// print text like: 20 4 X 6 window
#Override
public String toString() {
String s = "";
s = num + " " + window.toString();
return s;
}
// Two orders are equal if they contain the same number of windows of the same size.
#Override
public boolean equals(Object that) {
if (that instanceof WindowOrder) {
WindowOrder order = (WindowOrder) that;
return this.num == order.num && this.window == order.window;
}
else { return false; }
}
}
public class Room {
Window window;
int numOfWindows;
Room(Window window, int numOfWindows) {
this.window = window;
this.numOfWindows = numOfWindows;
}
WindowOrder order() {
return new WindowOrder(window, numOfWindows);
}
// Print text like: 5 (6 X 8 window)
#Override
public String toString() {
String s = "";
s = numOfWindows + " (" + window.toString() + ")";
return s;
}
// Two rooms are equal if they contain the same number of windows of the same size
#Override
public boolean equals(Object that) {
if (that instanceof Room) {
Room room = (Room) that;
return this.window == room.window && this.numOfWindows == room.numOfWindows;
}
else { return false; }
}
}
class MasterBedroom extends Room {
MasterBedroom() {
super(new Window(4, 6), 3);
}
// Call parent's toString method
//
// return text like: Master bedroom: 3 (4 X 6 window)
#Override
public String toString() {
String s = "";
s = "Master bedroom: " + numOfWindows + " " + window.toString();
return s;
}
}
class GuestRoom extends Room {
GuestRoom() {
super(new Window(5, 6), 2);
}
// Call parent's toString method
//
// return text like: Guest room: 2 (5 X 6 window)
#Override
public String toString() {
String s = "";
s = "Guest room: " + numOfWindows + " " + window.toString();
return s;
}
}
class LivingRoom extends Room {
LivingRoom() {
super(new Window(6, 8), 5);
}
// Call parent's toString method
//
// return text like: Living room: 5 (6 X 8 window)
#Override
public String toString() {
String s = "";
s = "Living room: " + numOfWindows + " " + window.toString();
return s;
}
}
For Apartment's orderForOneUnit() method, I wrote this, but it seems to simplistic and I feel like I should be using a for loop..
WindowOrder[] orderForOneUnit() {
WindowOrder[] order = new WindowOrder[rooms.length];
return order;
}
Am I even close to correctly understanding this? What should be under the Apartment methods?
Didn't looks at the templates but from what you've provided, you're close. All you've done so far is create a WindowOrder[] array of length rooms. You need to add new WindowOrder(desc, num) to these arrays before return order;
/**
* All apartment rooms have the same number of windows, with the
* same size window for each of those.
*/
public class Apartment
{
private int numRooms_;
private int windowsPerRoom_;
private Window window_;
/**
* Constructor
*/
public Apartment(numRooms, windowsPerRoom, desiredWindowHeight, desiredWindowLength)
{
numRooms_ = numRooms;
windowsPerRoom_ = windowsPerRoom;
window_ = new Window(desiredWindowHeight, desiredWindowLenght);
}
/**
* Orders for one room in apartment
*/
public WindowOrder orderForOneUnit()
{
WindowOrder order = new WindowOrder(window_, 1);
return order;
}
/**
* Orders for all rooms in apartment
*/
public List<WindowOrder> orderForAllUnits()
{
List<WindowOrder> orders = new ArrayList<WindowOrder>();
WindowOrder order;
for(i=0; i<numRooms_; i++)
{
orders.add(new WindowOrder(window_, windowsPerRoom_);
}
return orders;
}
}
Now when you're in your code and you're ready for a new Apartment(x, x, x, x) you can do the following (I'll assume you're just in main())
public class ApartmentComplex
{
public static void main(String[] args)
{
int numWindowsPerRoom = 3;
int desiredWindowHeight = 10;
int desiredWindowWidth = 10;
int numRooms = 5;
Apartment aptWithFiveRooms = new Apartment(numRooms, numWindowsPerRoom, desiredWindowHeight, desiredWindowWidth);
WindowOrder singleSingleOrder = apt.orderForOneUnit();
List<WindowOrder> allRoomsOrder = apt.orderForAllUnits();
numRooms = 3;
Apartment aptWithThreeRooms = new Apartment(numRooms, numWindowsPerRoom, desiredWindowHeight, desiredWindowWidth);
List<WindowOrder> threeRoomsOrder = apt.orderForAllUnits();
}
}
You do need a for loop. At the moment you are returning an Array where each entry in the array is null.
Here is an example of filling an array:
for (int i = 0; i < array.length; i++) { // iterate over an array
array[i] = getValueFor(i); // put value in the array
}
I am working on a boat program that has a super class (Boat) and two subclasses (SailBoat, Powerboat) and I must print out all of the boats information and price as well as the most expensive boat and it's information alone. This is the part I am having trouble with since I am not entirely sure how to go about it. Here is what I have so far...
Boat Class:
public class Boat {
String color;
int length;
public Boat() {
color = "white";
length = 20;
}
public Boat(String col, int leng) {
color = col;
length = leng;
}
public boolean setColor(String col) {
if ("white".equals(col) || "red".equals(col) || "blue".equals(col) || "yellow".equals(col)) {
col = color;
return true;
} else {
System.out.println("Error: can only be white, red, blue or yellow");
return false;
}
}
public String getColor() {
return color;
}
public boolean setLength(int leng) {
if (leng < 20 || leng > 50) {
leng = length;
System.out.println("Sail Boats can only be between 20 and 50 feet, inclusively.");
return false;
} else {
return true;
}
}
public int getLength() {
return length;
}
public String toString() {
String string;
string = String.format("Color = " + color + " Length = " + length);
return string;
}
public int calcPrice() {
int price;
price = 5000 + length;
return price;
}
}
PowerBoat Subclass
import java.text.NumberFormat;
public class PowerBoat extends Boat {
int engineSize;
public PowerBoat() {
super();
engineSize = 5;
}
public PowerBoat(String col, int len, int esize) {
this.color = col;
this.length = len;
engineSize = esize;
}
public boolean setEngineSize(int esize) {
if (esize < 5 || esize > 350) {
System.out.println(
"Error: That engine is too powerful. The engine size must be between 1 and 350, inclusively");
esize = engineSize;
return false;
} else {
return true;
}
}
public int calcPrice() {
int price;
price = 5000 + length * 300 + engineSize * 20;
return price;
}
public String toString() {
NumberFormat nf = NumberFormat.getCurrencyInstance();
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
return super.toString() + " Engine Size = " + engineSize + " Price = " + nf.format(calcPrice());
}
}
SailBoat subclass
import java.text.NumberFormat;
public class SailBoat extends Boat {
int numSails;
public SailBoat() {
numSails = 0;
}
public SailBoat(String col, int leng, int numsail) {
color = col;
length = leng;
numSails = numsail;
}
public boolean setNumSails(int nsails) {
if (nsails < 1 || nsails > 4) {
nsails = numSails;
return false;
} else {
return true;
}
} // end setNumSails
public int getNumSails() {
return numSails;
}
public int calcPrice() {
int price;
price = length * 1000 + numSails * 2000;
return price;
}
public String toString() {
NumberFormat nf = NumberFormat.getCurrencyInstance();
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
return super.toString() + "Color: " + color + " Length: " + length + " Number Sails = " + numSails + " Cost = "
+ nf.format(calcPrice());
}
public int getTotalCost() {
int totalCost = 0;
totalCost += calcPrice();
return totalCost;
}
}
Inventory class (tester)
import java.util.ArrayList;
public class Inventory {
public static void main(String[] args) {
// boat objects
Boat pb1 = new PowerBoat("blue", 22, 60);
Boat sb1 = new SailBoat("white", 20, 1);
Boat sb2 = new SailBoat("red", 42, 3);
Boat pb2 = new PowerBoat("yellow", 35, 80);
Boat pb3 = new PowerBoat("red", 50, 120);
Boat sb3 = new SailBoat("blue", 33, 2);
Boat pb4 = new PowerBoat("white", 20, 10);
ArrayList<Boat> AL = new ArrayList<Boat>();
// add boat objects to arraylist
AL.add(pb1);
AL.add(sb1);
AL.add(sb2);
AL.add(pb2);
AL.add(pb3);
AL.add(sb3);
AL.add(pb4);
// print all boat objects
System.out.println("Print all boats");
for (Boat anyBoat : AL) {
System.out.println(anyBoat.toString());
}
int max = 0;
int totalcost = 0;
Boat mostExpensiveBoat = null;
for (Boat anyBoat : AL) {
if (anyBoat instanceof SailBoat) {
totalcost += anyBoat.calcPrice();
if (anyBoat.calcPrice() > max) {
max = anyBoat.calcPrice();
mostExpensiveBoat = anyBoat;
}
}
}
}
}
I am really confused on how to finish up this program, the results I am supposed to get after all the boat information is printed is this..
Total price of all boats is $ 170,500.00
Most Expensive Boat: Color = red Length = 42 Number Sails = 3 Cost = $ 48,000.00
Any help will be greatly appreciated. Thank you.
There are a few design flaws you should correct:
Your Boat class should be an interface or abstract. You can't have a boat that isn't a power boat or sail boat so you should not be able to instantiate one.
Your instance variables should be private.
Make methods abstract that need to be defined by subclasses of Boat (e.g. calcPrice).
If you are able to use Java 8 then there's a nice way of getting the most expensive boat. The following code will print the most expensive boat (using Boat.toString) if one is present.
allBoats.stream()
.max(Comparator.comparingInt(Boat::calcPrince))
.ifPresent(System.out::println);
That avoids having to write the code that manually iterates through your list comparing prices. It also copes with the situation of an empty list (which means there is no maximum). Otherwise you need to initialise to null and compare to null before printing.
Your for loop should look like this:
for (Boat anyBoat : AL) {
totalcost += anyBoat.calcPrice();
if (anyBoat.calcPrice() > max) {
max = anyBoat.calcPrice();
mostExpensiveBoat = anyBoat;
}
}
It doesn't matter if it's a sailBoat or not, you just wanna print the information of the most expensive one, so you can remove the instanceof condition. After that:
NumberFormat nf = NumberFormat.getCurrencyInstance();
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
System.out.println("Total price of all boats is " + nf.format(totalcost));
System.out.println("Most expensive boat: " + mostExpensiveBoat.toString());
Should work, since you have already overriden the toString() methods.
one more thing: In your SailBoat toString() method, you are doing:
return super.toString() + "Color: " + color + " Length: " + length + " Number Sails = " + numSails + " Cost = "
+ nf.format(calcPrice());
When you call the super.toString() you are printing the color and the length twice; just call
return super.toString() + " Number Sails = " + numSails + " Cost = " + nf.format(calcPrice());
I am still at HelloWorld when it comes to my lack of Java skills. I cannot understand this to save my life. I am working on writing an override method? And am just starting out with the code provided from my school before I even start trying to complete the rest and I am already getting errors that I cannot even begin to think of how to correct. Any help at all would be greatly appreciated. I just want this error to go away so I can create some new ones :)
Here is the code:
public class Vehicle
public static void main (String [] args)}
{
private boolean moving; // whether or not the vehicle
private double speed;
private char bearing;
('N','E','S', or 'W')
public Vehicle(){ // Vehicle class no-arg constructor
moving = false; // assume not moving
speed = 0.0; // not moving
bearing = 'N'; // assume 'N'orth
System.out.println("Created a vehicle (no-arg)");
}
public Vehicle (double initialSpeed) // Vehicle 1-arg constructor
bearing = 'W';
speed = initialSpeed;
if (speed > 0.0)
{
moving = true;
}
System.out.println("Created a vehicle (1-arg)");
public Vehicle (double initialSpeed, char initialBearing) // Vehicle 2-arg constructor
bearing = initialBearing;
speed = initialSpeed;
if (speed > 0.0){
moving = true;
}
System.out.println("Created a vehicle (2-arg)");
public void start(double initialSpeed, char initialBearing){
moving = true;
if (initialSpeed >= 5.0 && initialSpeed <= 20.0){
speed = initialSpeed; // valid expected range
} else if (initialSpeed >= 0.0 && initialSpeed < 5.0){
speed = 5.0; // minimum
} else if (initialSpeed < 0.0){
speed = 0.0; // assume no movement
moving = false;
} else if (initialSpeed > 20.0){
speed = 20.0; // maximum allowed
}
switch(initialBearing){
case 'N':
bearing = initialBearing;
break;
case 'E':
bearing = initialBearing;
break;
case 'S':
bearing = initialBearing;
break;
case 'W':
bearing = initialBearing;
default:
System.out.println("invalid bearing " +
initialBearing +
" set to N"); // additional user notification
bearing = 'N';
}
public double getSpeed() { // get and return current speed in mph
return speed;
}
public void setSpeed(double newSpeed){ // set new speed in mph
speed = newSpeed;
}
/**
*
* #return
*/
public char getBearing(){
return bearing;
}
public void speedUp(double mphSteps, int numSteps){
int counter = 0;
while (counter < numSteps)
speed += mphSteps;
System.out.println("counter= " + counter + ", " +
this.toString());
counter++;
}
public String toString(){
return "From toString(): speed= " + getSpeed() +
" mph and bearing= " + getBearing();
}
}
public class Car extends Vehicle{
private String color;
private int doors;
private double hp;
public Car(String carColor, int numDoors,
double horsePower, double
startingSpeed)
{
super(startingSpeed);
color = carColor;
doors = numDoors;
hp = horsePower;
System.out.println("Created a car");
}
public String getColor()
{
return color;
}
public int getDoors()
{
return doors;
}
public double getHp()
{
return hp;
}
public String toString()
{
return "From Car toString(): color= " + getColor() +
" doors= " + getDoors() +
" hp= " + getHp() +
" speed= " + getSpeed() +
" mph and bearing= " + getBearing();}
}
public class TestCar2
{
public static void main(String[] args)
{
Car myCar2 = new Car("blue", 4, 300., 10.0);
System.out.println(myCar2.toString());
myCar2.speedUp(5.0, 2);
}
}
Please Please and thank you for helping!
public class Vehicle
public static void main (String [] args)} // this is totally wrong
// This not compile at least
{
Actually parenthesis({}) you are using is totally wrong. Following structure should follow you. I am guessing that you are not using IDE to do coding. I suggest you to use IDE to do code.
public class MyClass{
public static void main(String[] args){
// main method
}
// some other method
}
Firstly You cannot have two public classes in a single file!!
Secondly you braces are completely unmatching.
public class Vehicle
public static void main (String [] args)}
{
Class has it's own scope and main() function has it's own. So change your code to
public class Vehicle {
public static void main (String [] args) { //your code}
}
your multiple arg constructors don't have proper brackets.
public Vehicle (double initialSpeed) // Vehicle 1-arg constructor
bearing = 'W';
speed = initialSpeed;
if (speed > 0.0)
{
moving = true;
}
System.out.println("Created a vehicle (1-arg)");
change it to
public Vehicle (double initialSpeed) { // Vehicle 1-arg constructor
bearing = 'W';
speed = initialSpeed;
if (speed > 0.0)
{
moving = true;
}
System.out.println("Created a vehicle (1-arg)");
}
lastly your switch statement you need to put break in all cases(except default)
change
case 'W':
bearing = initialBearing;
to
case 'W':
bearing = initialBearing;
break;
If you are new to java and learning basics I suggest use an IDE like Eclipse, Netbeans or Intellij IDEA. Google them to find more info.
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.";
}