Find Highest Value in Enum - java

I'm making a class for a game I'm making and cannot figure out how to return the highest 'reward' to a user:
What I'm trying to get it to do is return the reward based on the player's kills. If he has 38 kills, it should return only 300. Not 150 aswell.
class EnumTest {
private static int playerKills = 38;
private enum KillReward {
BEGINNER(10, 150),
JUNIOR(25, 300),
EXPERT(50, 500),
CHAMPION(100, 1000);
private KillReward(int kills, int reward) {
this.kills = kills;
this.reward = reward;
}
private int kills, reward;
private int getKillsNeeded() {
return kills;
}
private int getKillReward() {
return reward;
}
}
public static void main (String[] args) {
for (KillReward k : KillReward.values()) {
if (playerKills > k.getKillsNeeded()) {
System.out.println("Kills: " + playerKills + "; Reward: " + k.getKillReward());
}
}
}
}

There are a couple ways of doing this.
One easy way is assign the reward to a variable. At the end of that loop the reward variable below will be the highest kill reward that was applicable
public static void main (String[] args) {
KillReward reward = null;
for (KillReward k : KillReward.values()) {
if (playerKills > k.getKillsNeeded()) {
reward = k;
}
}
System.out.println("Kills: " + playerKills + "; Reward: " + k.getKillReward());
}
Note that this relies on the enum being listed in order which can sometimes be fragile. For example, if a new KillReward enum is added after CHAMPION but has a lower killsNeeded value, then it will not return the proper value.
A better solution would be to create a Comparator and use it to sort the enum values by killsNeeded first, thus ensuring that they are always in order. If you also sort it in descending order, then you can also break from your loop once you hit the first applicable one.
class EnumTest {
private enum KillReward {
BEGINNER(10, 150), JUNIOR(25, 300), EXPERT(50, 500), CHAMPION(100, 1000);
// Sort KillRewards once at initialization
private static final List<KillReward> sortedKillRewards = new ArrayList<KillReward>();
static {
for (KillReward k : values())
sortedKillRewards.add(k);
Collections.sort(sortedKillRewards, new Comparator<KillReward>() {
#Override
public int compare(KillReward o1, KillReward o2) {
return (o1.kills - o2.kills) * -1; // multiplying by -1 makes it
// descending
}
});
}
private KillReward(int kills, int reward) {
this.kills = kills;
this.reward = reward;
}
private int kills, reward;
private int getKillsNeeded() {
return kills;
}
private int getKillReward() {
return reward;
}
public static KillReward forKills(int killCount) {
for (KillReward k : sortedKillRewards)
if (killCount >= k.kills)
return k;
// must not have enough kills for any reward
return null;
}
}
public static void main(String[] args) {
int kills = 9;
System.out.println("Kills: " + kills + "; Reward: "
+ KillReward.forKills(kills));
kills = 10;
System.out.println("Kills: " + kills + "; Reward: "
+ KillReward.forKills(kills));
kills = 38;
System.out.println("Kills: " + kills + "; Reward: "
+ KillReward.forKills(kills));
}
}

Related

How can I create a Java algorithm that takes any number of players and pair them up any number of times uniquely?

I am looking to create an algorithm in Java that can take any number of "players" and group them up a specified number of times each. However, two pairs cannot be the same. So, if we are supplied 9 players (dubbed 0, 1, 2, etc) by the user and each player should be paired 3 times, that means that this algorithm needs to be able to generate a list of pairs where each player is paired 3 times.
So 4 players being paired two times could be: {{0, 1}, {2, 3}, {0, 2}, {1, 3}}.
Obviously, it can be impossible in some scenarios (like 4 players being uniquely paired 20 times), but I have input restrictions to combat that.
{0, 1} and {1, 0} are equal pairs. The order of the numbers does not matter, they are not unique.
The preferable way for input is just given two numbers (number of players, number of pairs per players) and the preferable way for the output to be given is in a two dimensional array of integers (each player being dubbed by an integer), like I gave an example of.
Does anyone have any ideas on how to do this? Pseudo-code, actual code, any ideas are welcome. Thanks!
I think your question is valid and interesting to solve in code.
This is why I coded that whole thing.
There's one downside to my solution, or rather: the problem.
In certain situations, some players can have many matches between them, while others have little. So in the end, some players might not get matched properly.
In this case, you'd need a mathematical trick, or a backtracking algorithm, that steps back on parts of the solution and tries (brute-forces) other combinations. My algorithm has neither, but it indicates Exceptions and validity.
Also check the comments in the code.
package snippet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map.Entry;
public class BadPairingStuff6 {
static class Player {
public final int mID;
private final BadPairingStuff6 mParentLogic;
public int mMatches;
public Player(final int pID, final BadPairingStuff6 pBadPairingStuff5) {
mID = pID;
mParentLogic = pBadPairingStuff5;
}
#Override public int hashCode() {
return mID;
}
#Override public boolean equals(final Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
final Player other = (Player) obj;
if (mID != other.mID) return false;
return true;
}
#Override public String toString() {
return "Player[" + mID + "]";
}
public void incMatches() {
++mMatches;
}
public int getMatches() {
return mMatches;
}
public boolean canPlayAnotherMatch() {
return getMatches() < mParentLogic.mPairingsAllowed;
}
}
static class Pairing {
public final Player mPlayer1;
public final Player mPlayer2;
public Pairing(final Player pPlayer1, final Player pPlayer2) {
if (pPlayer1.mID < pPlayer2.mID) {
mPlayer1 = pPlayer1;
mPlayer2 = pPlayer2;
} else {
mPlayer1 = pPlayer2;
mPlayer2 = pPlayer1;
}
}
#Override public String toString() {
return mPlayer1 + "+" + mPlayer2;
}
#Override public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + mPlayer1.mID;
result = prime * result + mPlayer2.mID;
return result;
}
#Override public boolean equals(final Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
final Pairing other = (Pairing) obj;
if (mPlayer1 != other.mPlayer1) return false;
if (mPlayer2 != other.mPlayer2) return false;
return true;
}
}
static class PartnerMap {
private final HashMap<Player, ArrayList<Player>> mMap = new HashMap<>();
public PartnerMap(final Iterable<Player> pPlayers) {
for (final Player player : pPlayers) {
final ArrayList<Player> partners = new ArrayList<>();
for (final Player partner : pPlayers) {
if (player != partner) partners.add(partner);
}
mMap.put(player, partners);
}
}
public Player getPartner(final Player pPlayer) {
final ArrayList<Player> possiblePartners = mMap.get(pPlayer);
if (possiblePartners.size() < 1) throw new NotEnoughPartnersException(pPlayer);
return possiblePartners.get((int) (Math.random() * possiblePartners.size()));
}
public void removePartners(final Player pPlayer, final Player pPartner) {
System.out.println("\t\tBadPairingStuff5.PartnerMap.removePartners(" + pPlayer + ", " + pPartner + ")");
System.out.println("\t\t\tRemoving for " + pPlayer);
System.out.println("\t\t\t\tBEFORE: " + toString(mMap.get(pPlayer)));
mMap.get(pPlayer).remove(pPartner);
System.out.println("\t\t\t\tAFTER: " + toString(mMap.get(pPlayer)));
System.out.println("\t\t\tRemoving for " + pPartner);
System.out.println("\t\t\t\tBEFORE: " + toString(mMap.get(pPartner)));
mMap.get(pPartner).remove(pPlayer);
System.out.println("\t\t\t\tAFTER: " + toString(mMap.get(pPartner)));
}
static String toString(final Iterable<Player> pPlayers) {
final StringBuilder sb = new StringBuilder();
sb.append("[");
for (final Player player : pPlayers) {
sb.append(player.mID + " ");
}
sb.append("]");
return sb.toString();
}
public void removePlayerCompletely(final Player pPlayer) {
System.out.println("\t\t\tBadPairingStuff5.PartnerMap.removePlayerCompletely(" + pPlayer + ")");
for (final ArrayList<Player> partnerMap : mMap.values()) {
partnerMap.remove(pPlayer);
}
mMap.get(pPlayer).clear();
}
public void print() {
System.out.println("Partner Map");
for (final Entry<Player, ArrayList<Player>> e : mMap.entrySet()) {
System.out.println("\t" + e.getKey());
for (final Player v : e.getValue()) {
System.out.println("\t\t" + v);
}
}
}
}
public static class NotEnoughPartnersException extends IllegalStateException {
private static final long serialVersionUID = -7249807214069096317L;
private final Player mPlayer;
public NotEnoughPartnersException(final Player pPlayer) {
super("Not enough partners available for " + pPlayer + "!");
mPlayer = pPlayer;
}
public Player getPlayer() {
return mPlayer;
}
}
static class PairingResult {
public final ArrayList<Pairing> mCreatedPairings;
public final ArrayList<Exception> mExceptions;
public PairingResult(final ArrayList<Pairing> pCreatedPairings, final ArrayList<Exception> pExceptions) {
mCreatedPairings = pCreatedPairings;
mExceptions = pExceptions;
}
public boolean isValid() {
return mExceptions.size() < 1;
}
}
public static void main(final String[] args) {
final int players = 10;
final int pairingsAllowed = 4;
final PairingResult result = new BadPairingStuff6(players, pairingsAllowed).createPairings();
System.out.println("All pairings:");
final HashMap<Long, Long> playCounter = new HashMap<>();
for (final Pairing p : result.mCreatedPairings) {
System.out.println("\t" + p);
{
final Long oldCount = playCounter.get(Long.valueOf(p.mPlayer1.mID));
playCounter.put(Long.valueOf(p.mPlayer1.mID), Long.valueOf(oldCount == null ? 1 : (oldCount.longValue() + 1)));
}
{
final Long oldCount = playCounter.get(Long.valueOf(p.mPlayer2.mID));
playCounter.put(Long.valueOf(p.mPlayer2.mID), Long.valueOf(oldCount == null ? 1 : (oldCount.longValue() + 1)));
}
}
System.out.println("Pairings per Player: ");
for (final Entry<Long, Long> e : playCounter.entrySet()) {
System.out.println("\t" + e.getKey() + " -> " + e.getValue());
}
System.out.println("Exceptions:");
System.out.flush();
sleep();
for (final Exception e : result.mExceptions) {
e.printStackTrace();
}
System.err.flush();
sleep();
System.out.println("Valid result: " + result.isValid());
System.out.println("All done.");
}
/*
* OBJECT
*/
final int mPairingsAllowed;
private final ArrayList<Player> mPlayers = new ArrayList<>();
public BadPairingStuff6(final int pPlayersCount, final int pPairingsAllowed) {
mPairingsAllowed = pPairingsAllowed;
// create players
for (int i = 0; i < pPlayersCount; i++) {
mPlayers.add(new Player(i, this));
}
}
public PairingResult createPairings() {
final ArrayList<Pairing> createdPairings = new ArrayList<>();
final ArrayList<Exception> exceptions = new ArrayList<>();
final PartnerMap possiblePairings = new PartnerMap(mPlayers);
final HashSet<Player> playersToHandle = new HashSet<>(mPlayers);
while (!playersToHandle.isEmpty()) {
final ArrayList<Player> removePlayersPerRound = new ArrayList<>();
for (final Player player : playersToHandle) {
if (!player.canPlayAnotherMatch()) {
possiblePairings.removePlayerCompletely(player);
removePlayersPerRound.add(player);
continue;
}
try {
System.out.println("Creating matches for " + player + " (" + player.getMatches() + ")");
final Player partner = possiblePairings.getPartner(player);
if (!partner.canPlayAnotherMatch()) continue;
final Pairing newPairing = new Pairing(player, partner);
if (createdPairings.contains(newPairing)) System.out.println("WARNING! Double hit for " + newPairing);
createdPairings.add(newPairing);
possiblePairings.removePartners(player, partner);
player.incMatches();
partner.incMatches();
System.out.println("\tMatched with " + partner);
if (!partner.canPlayAnotherMatch()) {
possiblePairings.removePlayerCompletely(partner);
removePlayersPerRound.add(partner);
}
} catch (final NotEnoughPartnersException e) {
// the flushes and sleeps are only a cheap shot to keep System.out and System.err outputs in somewhat chronological order.
// this is for proof/debug/answer only, and should NOT be used in production!
System.out.flush();
sleep();
e.printStackTrace();
// throw e; // if you want to abort early
removePlayersPerRound.add(e.getPlayer());
exceptions.add(e);
System.err.flush();
sleep();
}
}
playersToHandle.removeAll(removePlayersPerRound);
}
possiblePairings.print();
return new PairingResult(createdPairings, exceptions);
}
// the sleeps are only a cheap shot to keep System.out and System.err outputs in somewhat chronological order.
// this is for proof/answer only, and should NOT be used in production
static void sleep(final long pMilliSec) {
try {
Thread.sleep(pMilliSec);
} catch (final InterruptedException e1) { /* */ }
}
static void sleep() {
sleep(100);
}
}
I use lots of inner static classes. This is for demonstration purposes only.
If you want to actually use those classes, put each of them into its separate file (remove the "static class", and add a "public class" where it's missing).
Also note that this complexity is needed for random assignments. If the algorithm could always churn out the same combinations, it would be about 1/10th of the code.

How do I change a Variable, in a Java Class

I have to be able to convert some variables in my class. I have a boolean variable, WaGa (Stands for Workstation/Gaming computer), and if it's true, I want to convert String WorGam
I have to do this through service and support methods, and I keep trying, but I constenly fail. It just prints out what's in the driver. HELP.
public class Graphics
//instance data
{
private int Ram;
private String Brand;
private int Res;
private int BiWi;
private int BaCl;
private boolean K4;
private boolean WaGa;
private String WorGam;
//boolean WaGa, boolean K4, int BaCl, int BiWi, int Res, String Brand, int Ram
public Graphics (int R, String B, int Re, int Bi, int Ba, boolean K4, boolean Wa, String Wor ) // constructor
{
Ram = R;
Brand = B;
Res = Re;
BiWi = Bi;
BaCl = Ba;
K4 = K4;
WaGa = Wa;
Wor = WorGam;
}
public int get_Ram() //Accessor Method - there are 3 of them
{
return Ram;
}
public String get_Brand() //Accessor Method - there are 3 of them
{
return Brand;
}
public int get_Res() //Accessor Method - there are 3 of them
{
return Res;
}
public int get_BiWi() //Accessor Method - there are 3 of them
{
return BiWi;
}
public int get_BaCl()
{
return BaCl;
}
public boolean get_K4()
{
return K4;
}
public String WorGam(boolean WaGa)
{
String WorGam;
if ( WaGa == true) {
return WorGam = "Workstation";
} else {
return WorGam = "True";
}
}
public String toString()
{
return ("Ram" + " " + Ram + ". " + "Brand:" + " " + Brand + ". " + "Resolution" + " " + Res + ". " + "Processer" + " " + BiWi + "." + " " + "Base Clock" + " " + BaCl+ " " + "K4?" + " " + K4+ " " +WorGam);
}
}
public class Graphicse_Driver
{
public static void main(String [] args)
{
Graphics unique=new Graphics(4, "Nvinda", 6, 7, 9, false, false, "sdf" );
System.out.println(unique);
You may need to reread you code to make sure there aren't any other mistakes in your code, but this is the root of your problem.
In order to access the WarGam getter, you need to call:
System.out.println(unique.WarGam());
When you do System.out.println(unique), you are trying to print out the entire Graphics object instead of just the WarGam string.
You then should change your WarGam() method to look like the following:
public String WorGam()
{
if (WaGa) {
return "Workstation";
}
return "Gaming";
}
Here is a more in depth explanation of the changes:
WaGa is a private variable of your Graphics class. Since the WarGam() method is in the same Graphics class, it already had access to the WaGa variable, so you do not need to pass it in.
if(WaGa == true) is just a wordier way of writing if(WaGa).
Instead of creating a String WorGam variable, you can just return the string you want directly.
The else surrounding the second return is unnessary since that code will only be hit if the first return is skipped.
After these changes, the private String WarGam variable is really not necessary either.
public String worGam(boolean waGa) {
if (waGa)
return "Workstation";
else
return "Gaming";
}
You need to correct your worGam() function:
public String worGam(boolean waGa) {
if (waGa == true)
return "Workstation";
else
return "True";
}
And the main() function:
public static void main(String [] args) {
Graphics unique = new Graphics(4, "Nnn", 6, 7, 9, false, false, "xxx");
System.out.println(unique.WorGam(false));
}

toString an arraylist containing object

I have an array list of type car.
I have an overriding toString method which prints my car in the desired format.
I'm using the arraylist.get(index) method to print the cars.
I only have one for now it works, but I want it do print for all of the cars in the array list.
This is my code:
public class Garage {
private static int carsCapacity = 30;
ArrayList<Cars> myGarage;
public Garage() {
Scanner scanAmountOfCars = new Scanner(System.in);
System.out.println("Please limit the number of car the garage can contain.");
System.out.println("If greater than 50, limit will be 30.");
int validAmount = scanAmountOfCars.nextInt();
if (validAmount <= 50) {
carsCapacity = validAmount;
myGarage = new ArrayList<Cars>();
}
System.out.println(carsCapacity);
}
public void addCar() {
Cars car = new Cars(Cars.getID(), Cars.askCarID(), Cars.getPosition(), Attendant.askForAtt(), System.currentTimeMillis());
myGarage.add(car);
//System.out.println(car);
}
public static int getCarsCapacity() {
return carsCapacity;
}
#Override
public String toString() {
return "Garage [Car:" + myGarage.get(0).getPlateNum() + " ID:" + myGarage.get(0).getCarID() + " Position:" + Cars.getPosition() +
" Assigned to:" + Cars.getAssignedTo().getId() + "(" + Cars.getAssignedTo().getName()
+ ")" + " Parked at:" + Cars.convert(myGarage.get(0).getCurrTime()) + "]";
}
}
I also put the Cars class in case you need it:
public class Cars {
private String carID;
private String plateNum;
private static String position;
private static Attendant assignedTo;
private long currTime;
static String[] tempArray2 = new String[Garage.getCarsCapacity()];
public Cars(String carID, String plateNum, String position, Attendant assignedTo, long currTime) {
this.carID = carID;
this.plateNum = plateNum;
Cars.position = position;
Cars.assignedTo = assignedTo;
this.currTime = currTime;
}
private static void createCarsID() {
for (int x = 0; x < Garage.getCarsCapacity(); x++) {
tempArray2[x] = ("CR" + (x + 1));
}
}
public static String getID() {
createCarsID();
String tempID = null;
String tempPos = null;
for (int x = 0; x < tempArray2.length; x++) {
if (tempArray2[x] != null) {
tempID = tempArray2[x];
tempPos = tempArray2[x];
getPos(tempPos);
tempArray2[x] = null;
break;
}
}
return tempID;
}
public static void getPos(String IdToPos) {
String strPos = IdToPos.substring(2);
int pos = Integer.parseInt(strPos);
position = "GR" + pos;
}
public String getPlateNum() {
return plateNum;
}
public String getCarID() {
return carID;
}
public static String getPosition() {
return position;
}
public long getCurrTime() {
return currTime;
}
public static Attendant getAssignedTo() {
return assignedTo;
}
public static String askCarID() {
boolean valid = false;
System.out.println("Please enter your car's plate number.");
Scanner scanCarID = new Scanner(System.in);
String scannedCarID = scanCarID.nextLine();
while (!valid) {
if (scannedCarID.matches("^[A-Za-z][A-Za-z] [0-9][0-9][0-9]$")) {
valid = true;
System.out.println(scannedCarID);
} else {
System.out.println("Please enter a valid plate number. Ex: AF 378");
askCarID();
}
}
return scannedCarID.toUpperCase();
}
public static String convert(long miliSeconds) {
int hrs = (int) TimeUnit.MILLISECONDS.toHours(miliSeconds) % 24;
int min = (int) TimeUnit.MILLISECONDS.toMinutes(miliSeconds) % 60;
int sec = (int) TimeUnit.MILLISECONDS.toSeconds(miliSeconds) % 60;
return String.format("%02d:%02d:%02d", hrs, min, sec);
}
}
Your Garage should have the implementation of toString() which uses ArrayList#toString() implementation:
public String toString() {
return "Garage: " + myGarage.toString();
}
Also remember to implement toString() in Cars.java.
public String toString() {
return "[" + this.carID + " " +
this.plateNum + " " +
Cars.position + " " +
Cars.assignedTo.toString + " " +
String.valueOf(this.currTime) + "]"
}

Printing out most expensive boat and it's information from an 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());

How to compare parameter values of two objects in Java?

Right now I'm working on a method for comparing the scores of athletes in the olympics. So far I've had little trouble, however now I've reached a point where i need to compare two objects (athletes) scores and I'm not sure how to do it. This is my code for the Olympic class:
// A program using the Athlete class
public class Olympics {
public static void main(String args[]) {
System.out.println("The leader is " + Athlete.leader() +
", with a score of " + Athlete.leadingScore());
Athlete meryl = new Athlete("Meryl Davis", "U.S.");
meryl.addScore(75);
System.out.println(meryl);
Athlete tessa = new Athlete("Tessa Virtue", "Canada");
System.out.println(tessa);
System.out.println(); // blank line
tessa.addScore(50);
System.out.println(tessa);
System.out.println(meryl);
System.out.println("The leader is " + Athlete.leader() +
", with a score of " + Athlete.leadingScore());
System.out.println(); // blank line
tessa.addScore(100);
meryl.addScore(65);
System.out.println(tessa);
System.out.println(meryl);
System.out.println("The leader is " + Athlete.leader() +
", with a score of " + Athlete.leadingScore());
System.out.println(); // blank line
tessa.addScore(20);
System.out.println("Tessa's final score is " + tessa.getScore());
meryl.move("France");
System.out.println(meryl);
} // end main
} // end class Olympics
And this is the constructor class "Athlete":
public class Athlete {
private String name;
private String country;
protected int score;
public static int leadScore;
public Athlete(String athName, String athCountry) {
this.name = athName;
this.country = athCountry;
score = 0;
if (score < 1) {
System.out.println("Score cannot be lower than 1");
}
}
public int addScore(int athScore) {
score += athScore;
return score;
}
public static String leader(){
//TODO
}
public static int leadingScore() {
//MUST COMPARE BOTH ATHLETES
}
public int getScore(){
return score;
}
public void move(String newCountry) {
country = newCountry;
}
public String toString() {
return name + ": " + "from " + country + ", current score " + score;
}
}
So what I'm trying to do is have the program check Meryl's score compared to Tessa's and return that Athlete's score in leadingScore() and, using that athlete, return a leader(). Any help is appreciated! Thanks.
The function must take the two Athletes you're comparing as the parameters for this to work
public static int leadingScore(Athlete a1, Athlete a2) {
if (a1.getScore() < a2.getScore()) {
// do stuff
}
}
The lead score should not be in the athlete class, but rather in main () because one instance of an Athlete class would not know of other instances unless you put a self-referential list inside the class. Similarly, leadingScore should be in main ().
It or main can call each athlete and compare:
int merylScore = meryl.getScore ();
int tessaScore = tessa.getScore ();
int leadingScore = 0;
String leaderName = "";
if (merylScore > tessaScore) {
leadingScore = merylScore;
leaderName = meryl.getName ();
} else if (tessaScore > merylScore) {
leadingScore = tessaScore;
leaderName = tessa.getName ();
} else {
leadingScore = merylScore;
leaderName = "a tie between Meryl and Tessa";
}
System.out.println ("The leader is " + leaderName + ", with a score of " + leadingScore);
You should consider using a "collection". Use an array, a list ... or even a sorted list.
Stored your individual objects in the collection, then traverse the collection to find the highest score.
For example:
// Create athlete objects; add each to list
ArrayList<Athlete> athletes = new ArrayList<Athlete>();
Athlete meryl = new Athlete("Meryl Davis", "U.S.");
meryl.addScore(75);
...
athletes.add(meryl);
Athlete tessa = new Athlete("Tessa Virtue", "Canada");
...
athletes.add(tessa );
// Go through the list and find the high scorer
Athlete highScorer = ...;
for (Athlete a : athletes) {
if (highScorer.getScore() < a.getScore())
highScorer = a;
...
}
System.out.println("High score=" + highScorer.getScore());
Here's a good tutorial:
http://www.vogella.com/tutorials/JavaCollections/article.html

Categories