I'm trying to making a program that simulates the card game War.
class Project2
package proj2;
import java.util.Scanner;
public class Project2 {
public static void main( String[ ] args)
{
Scanner keybd = new Scanner( System.in );
// Get player names
System.out.println("Welcome to WAR!!");
System.out.print("Please enter player 1's name: ");
String p1Name = keybd.nextLine();
System.out.print("Please enter player 2's name: ");
String p2Name = keybd.nextLine();
// Get random number generator (RNG) seed and initialize the game
System.out.print ("Please enter the RNG seed for shuffling: ");
long rngSeed = keybd.nextLong();
Game war = new Game(p1Name, p2Name, rngSeed);
int turn = 1;
// While game is being played, print details and results of each turn
while (!war.gameComplete())
{
System.out.printf( "Turn %2d\n", turn);
System.out.println( "-----");
System.out.println( war.nextTurn());
++turn;
}
// All turns complete; print the game results
System.out.println("Game Over!!");
System.out.println(war.gameResult());
}
}
Class Game:
package proj2;
public class Game {
private Deck deck;
private Player player1;
private CardPile p1Deck;
private Player player2;
private CardPile p2Deck;
private int warCount;
private int turns;
public Game(String p1, String p2, long rngSeed)
{
this.deck = new Deck();
deck.Shuffle((int) rngSeed);
this.player1 = new Player(p1, 0, 0);
this.p1Deck = new CardPile(deck.Deal());
this.player2 = new Player(p2, 0, 0);
this.p2Deck = new CardPile(deck.Deal());
this.turns = 1;
this.warCount = 0;
}
public String nextTurn()
{
p1Card = p1Deck.drawCard();
(ERROR)---> String p1Turn = player1.getName() + " shows " + p1Card.cardString();
Card p2Card = p2Deck.drawCard();
String p2Turn = player2.getName() + " shows " + p2Card.cardString();
String winner = "";
if(p1Card.getValue() > p2Card.getValue())
{
Card[] wonCards = new Card[2];
wonCards[0] = p1Card;
wonCards[1] = p2Card;
p1Deck.addCard(wonCards, 2);
player1.setCardsWon(wonCards.length);
winner = player1.getName() + " wins 2 cards" ;
}
if(p2Card.getValue() > p1Card.getValue())
{
Card[] wonCards = new Card[2];
wonCards[0] = p2Card;
wonCards[1] = p1Card;
p1Deck.addCard(wonCards, 2);
player2.setCardsWon(wonCards.length);
winner = "/n" + player2.getName() + " wins 2 cards";
}
String warTurn = "";
if(p1Card.getValue() == p2Card.getValue())
{
this.warCount = warCount + 1;
warTurn = "WAR!!";
Card[] wonCards = new Card[8];
while(p1Card.getValue() != p2Card.getValue())
{
wonCards[0] = p1Deck.drawCard();
wonCards[2] = p1Deck.drawCard();
wonCards[4] = p1Deck.drawCard();
Card p1WarCard = p1Deck.drawCard();
wonCards[6] = p1WarCard;
wonCards[1] = p2Deck.drawCard();
wonCards[3] = p2Deck.drawCard();
wonCards[5] = p2Deck.drawCard();
Card p2WarCard = p2Deck.drawCard();
wonCards[7] = p2WarCard;
if(p1WarCard.getValue() > p2WarCard.getValue())
{
p1Deck.addCard(wonCards, wonCards.length);
player1.setCardsWon(wonCards.length);
}
if(p2WarCard.getValue() > p2WarCard.getValue())
{
p2Deck.addCard(wonCards, wonCards.length);
player2.setCardsWon(wonCards.length);
}
}
}
String turnResults = p1Turn + "/n" + p2Turn + "/n" + warTurn + winner;
return turnResults;
}
public boolean gameComplete()
{
boolean result = false;
if(turns == 20) {
result = true;
}
return result;
}
public String gameResult()
{
String p1Result = (player1.getName() + " won " + player1.getCardsWon() + "and"
+ player1.getWarsWon() + "war(s)" + "/n");
String p2Result = (player2.getName() + " won " + player2.getCardsWon() + "and"
+ player1.getWarsWon() + "war(s)" + "/n");
String winner = "";
if(player1.getCardsWon() > player2.getCardsWon())
{
winner = "Winner: " + player1.getName();
}
if(player2.getCardsWon() < player2.getCardsWon())
{
winner = "Winner: " + player2.getName();
}
if(player1.getCardsWon() == player2.getCardsWon())
{
winner = "Game is a draw";
}
String finalResult = ("Game Over!!" + "There were " + warCount
+ "war(s)" + p1Result + "/n" + p2Result + "/n" + winner);
return finalResult;
}
}
When I try to access the class Card, I get a null pointer exception error. I'm not sure what is producing the error.
public class Card {
private char rank;
private String suit;
private int value;
public Card(char rank, String suit, int value)
{
this.rank = rank;
this.suit = suit;
this.value = value;
}
public char getRank()
{
return rank;
}
public String getSuit()
{
return suit;
}
public int getValue()
{
return value;
}
public String cardString()
{
String card = (rank + " of " + suit);
return card;
}
}
I tried googling for solutions, and it tells me to initialize the object before referencing the object. I tried initializing, but it still produces the null pointer exception error.
The error I'm getting is this.
Exception in thread "main" java.lang.NullPointerException
at proj2.Game.nextTurn(Game.java:29)
at proj2.Project2.main(Project2.java:37)
The drawCard() method is from this class.
package proj2;
public class CardPile {
private Card[] playerDeck;
public CardPile(Card[] deck)
{
this.playerDeck = deck;
}
public Card drawCard()
{
Card topCard = playerDeck[0];
Card[] newPlayerDeck = new Card[playerDeck.length - 1];
int counter = 0;
for(int i = 1; i < playerDeck.length; i++)
{
newPlayerDeck[counter] = playerDeck[i];
counter++;
}
this.playerDeck = newPlayerDeck;
return topCard;
}
}
It returns a NULL Point Exception because you are not passing any parameters. Try passing parameters to your constructor.
e.g
Card p1Card = new Card(rank,suit,value);
Card p2Card = new Card(rank,suit,value);
Since p1Card null, then p1Deck.drawCard() returns null - which means playerDeck[0] is null, which means new CardPile(deck.Deal()); creates and empty deck, which means something is wrong in deck.Deal(). By "something is wrong" I mean that it probably creates and returns an array with null values, like: [null, null, null, null, null] (or it might be that the first value is the only one that's null).
Related
So, I'm trying to figure out how to get values of an array list from another class and print certain values depending on user input.
For example, firstly a user is asked to provide a location, once they enter a location, it has to read the user input and output the results according to the location.an image is provided about the output.
For some reason it doesn't output the correct values from array list.
Could you please help me out?
This is my code for reading values from array list.
public class Program {
ArrayList<Properties> property = Properties.getMelbnbProperty();
int i = 1;
for(i = 1; i < (property.size());) {
System.out.println(property.get(i));
break;
}
ArrayList<Properties> output = Properties.getMelbnbProperty();
if(Properties.getMelbnbProperty().contains(choice)) {
output.addAll(Properties.getMelbnbProperty());
}
} }
This is my code for array list.
public class Properties {
public static ArrayList<Properties> getMelbnbProperty() {
// Below is an arraylist where I have stored the Melbnb data
ArrayList<Properties> property = new ArrayList<Properties>();
property.add(new Properties("Private room in the heart of Southbank"));
property.add(new Properties("Spacious bedroom in a cosy apartment in South Yarra\n"));
property.add(new Properties("Ensuite room with great views"));
property.add(new Properties("Single room next to Carlton Gardens"));
property.add(new Properties("Studio close to Melbourne CBD"));
property.add(new Properties("1-bedroom CBD view suite near Melbourne Central and RMIT"));
property.add(new Properties("Stylish two bedroom in CBD"));
property.add(new Properties("Sky high studio with amazing views"));
property.add(new Properties("Budget accommodation bunk beds"));
property.add(new Properties("A beautiful room near Marvel Stadium"));
return property;
}}
The code you have provided in your question post is incomplete and in a way doesn't make sense to what your image displays. I do however understand what you are trying to accomplish but the way I see it your properties class is somewhat under-nourished.
I don't know if this is the intentional purpose but your for loop:
int i = 1;
for(i = 1; i < (property.size());) {
System.out.println(property.get(i));
break;
}
is designed to pull out 1 object from the property ArrayList. This loop is completely unnecessary since just supplying an index value of 1 to the ArrayList#get() method does exactly the same thing and is only a single line of code, for example:
System.out.println(property.get(1));
I say this because your for loop initializer starts at index 1, there is no iterator for the loop, and you apply the break statement directly after the display of the object within the ArrayList.
To access all elements within the ArrayList (your post indicates) you would need to do something like this:
for (int i = 0; i < properties.size(); i++) {
System.out.println(properties.get(i));
}
Or you can use:
for (String props: properties) {
System.out.println(props);
}
To be honest, what you are showing for code in grossly underdeveloped. I don't want to come across as insulting but it's obvious that you are not showing as much as you should be and therefore it is extremely difficult to provide you with any concrete solution to your problem. For this reason, I think it is just easier to provide you with a working demo console application which would allow you to perhaps grasp some concepts from.
The runnable code below consists of two specific classes, the start up class named SimpleBNBDemo which contains the main() method and the Properties class which allows you to instantiate instances of different BNB properties. As you can see, the Properties class is somewhat more fulfilled than the class you provided in your question post. Take the time to read through the code and try to follow its flow. Do keep in mind, although runnable this is only a Demo application and is in now way a complete works. I personally would never hard-code fill an ArrayList with Object data. This data should come from and or saved to a file system or database. However, for demo purposes this will suffice.
The SimpleBNBDemo class:
public class SimpleBNBDemo {
// Field variables
public final static String LS = System.lineSeparator();
public final static java.util.Scanner USER_INPUT = new java.util.Scanner(System.in);
// class member variable
private Properties prop = new Properties();
private final String line = "------------------------------------------------";
private int pwAttempts = 0;
public static void main(String[] args) {
// Started this way to avoid the need for statics
new SimpleBNBDemo().startApp(args);
}
private void startApp(String[] args) {
/* Create Properties instances...
You can do this with whatever means you like. */
java.util.List<Properties> properties = prop.getProperties();
properties.add(new Properties("Southbank Mannor", "Room", "Private room in the heart of Southbank.", "South", 86.00d, true));
properties.add(new Properties("Yarra House", "Room", "Spacious bedroom in a cosy apartment in South Yarra.", "South", 74.00d, true));
properties.add(new Properties("Ensuite Haven", "Room", "Ensuite room with great views.", "West", 65.50d, true));
properties.add(new Properties("Carlton Place", "Room", "Single room next to Carlton Gardens.", "South", 78.00d, true));
properties.add(new Properties("Melbourne Studio", "Studio", "Studio close to Melbourne CBD.", "East", 78.00d, true));
properties.add(new Properties("Melbourne Delight", "Room", "1-bedroom CBD view suite near Melbourne Central and RMIT.", "North", 135.00d, true));
properties.add(new Properties("CBD House", "Suit", "Stylish two bedroom in CBD.", "West", 100.00d, true));
properties.add(new Properties("Sky-High", "Studio", "Sky high studio with amazing views.", "North", 95.00d, true));
properties.add(new Properties("Budgeteer", "Room", "Budget accommodation bunk beds.", "South", 65.00d, true));
properties.add(new Properties("Stadium House", "Room", "A beautiful room near Marvel Stadium.", "East", 95.00d, true));
println("Welcome to MelBNB" + LS + line);
println();
// Menu 1 - Main Menu
String choice = "";
String[] locations = prop.getAllLocations();
if (locations.length == 0) {
printErr("No BNB's with Location in database yet!");
return;
}
while (choice.isEmpty()) {
println("Select from Main Menu:");
println(" 1) List all Accomodations");
println(" 2) Search by location");
println(" 3) Browse by type of accomodation");
println(" 4) Filter by rating");
println(" 5) Rate an accomodation");
println(" 6) Exit (quit)");
print("Please choose: -> ");
choice = USER_INPUT.nextLine().trim();
// Validate Entry...switch/case works great for input validation.
switch (choice) {
case "1":
listAllAccomodations();
break;
case "2":
searchByLocation();
break;
case "3":
searchByAccomodationType();
break;
case "4":
searchByRating();
break;
case "5":
rateAnAccomodation();
break;
case "6":
break;
case "~admin~":
adminMenu();
break;
case "~admin attempts reset~":
pwAttempts = 0;
println();
break;
default:
println("Invalid Entry (" + choice + ")! Try again..." + LS);
}
// Was 'Exit' (4) selected?
if (choice.equals("6")) {
// Break out of loop to end application.
println(LS + "Thank you for visiting MelBNB, Bye-Bye." + LS);
break;
}
choice = ""; // Reset 'choice' to be empty in order to loop again..
}
}
private void adminMenu() {
String pwrd = "";
while (pwrd.isEmpty()) {
if (pwAttempts >= 3) {
println(LS + "Admin Menu is NOT Available!" + LS + "To many failed "
+ "consecutive password attempts!" + LS + "Only " + pwAttempts
+ " consecutive attempts are allowed." + LS);
return;
}
print(LS + "Please enter Admin Password (c to cancel): --> ");
pwrd = USER_INPUT.nextLine().trim();
if (pwrd.equalsIgnoreCase("c")) {
println();
return;
}
int psum = 0;
for (int i = 0; i < pwrd.length(); i++) {
psum += pwrd.charAt(i);
}
if (psum != 624) {
pwAttempts++;
println("Invalid Password! Try again...");
pwrd = "";
}
}
pwAttempts = 0;
println();
println("***********************************************");
println("*** Administrative options would go here! ***");
println("*** Press Enter To Continue ***");
println("***********************************************");
String nothing = USER_INPUT.nextLine().trim();
}
private void listAllAccomodations() {
println(LS + "All Available Accomodations:");
println("----------------------------");
int cntr = 0;
String underline = "";
for (Properties pp : prop.getProperties()) {
cntr++;
String str = pp.toStringTable(pp, cntr == 1);
underline = String.join("", java.util.Collections.nCopies(str.length(), "="));
println(str);
if (cntr == 15) {
println("<- Press Enter To Continue ->");
String nuthin = USER_INPUT.nextLine().trim();
cntr = 0;
}
}
println(underline + LS);
}
private void searchByLocation() {
String[] locationTypes = prop.getAllLocations();
java.util.Arrays.sort(locationTypes);
String locationChoice = "";
while (locationChoice.isEmpty()) {
println();
println("Select the desired location:");
int i = 0;
for ( ; i < locationTypes.length; i++) {
println(" " + (i + 1) + ") " + locationTypes[i]);
}
println(" " + (i + 1) + ") Cancel");
print("Please choose: -> ");
locationChoice = USER_INPUT.nextLine().trim();
// Validate Entry...
if (!locationChoice.matches("[1-" + (locationTypes.length + 1) + "]")) {
println("Invalid Entry (" + locationChoice + ")! Try again..." + LS);
locationChoice = "";
}
}
if (locationChoice.equals(String.valueOf(locationTypes.length + 1))) {
println();
return;
}
String location = locationTypes[Integer.valueOf(locationChoice)-1];
java.util.List<Properties> p = prop.getPropertiesByLocation(location);
if (p.isEmpty()) {
println("No accomodations available in the " + location + " area!" + LS);
return;
}
String str = "Available accomodation within the " + location + " area:";
println(LS + str);
println(String.join("", java.util.Collections.nCopies(str.length(), "-")));
int cntr = 0;
for (Properties pp : p) {
cntr++;
println(pp.toStringTable(pp, cntr == 1));
}
println(line + LS);
}
private void searchByAccomodationType() {
String[] accTypes = prop.getAllAccomodationTypes();
java.util.Arrays.sort(accTypes);
String accChoice = "";
while (accChoice.isEmpty()) {
println();
println("Select the desired accomodation type:");
int i = 0;
for ( ; i < accTypes.length; i++) {
println(" " + (i + 1) + ") " + accTypes[i]);
}
println(" " + (i + 1) + ") Cancel");
print("Please choose: -> ");
accChoice = USER_INPUT.nextLine().trim();
// Validate Entry...
if (!accChoice.matches("[1-" + (accTypes.length + 1) + "]")) {
println("Invalid Entry (" + accChoice + ")! Try again..." + LS);
accChoice = "";
}
}
if (accChoice.equals(String.valueOf(accTypes.length + 1))) {
println();
return;
}
String acc = accTypes[Integer.valueOf(accChoice)-1];
java.util.List<Properties> p = prop.getPropertiesByAccomodationType(acc);
if (p.isEmpty()) {
println("No accomodation type of " + acc + " is available!" + LS);
return;
}
String str = "Available accomodation that are of type '" + acc + "':";
println(LS + str);
println(String.join("", java.util.Collections.nCopies(str.length(), "-")));
int cntr = 0;
for (Properties pp : p) {
cntr++;
println(pp.toStringTable(pp, cntr == 1));
}
println(line + LS);
}
private void searchByRating() {
String rateChoice = "";
while (rateChoice.isEmpty()) {
println();
println("Enter the desired accomodation rating (1 to 5);");
print( "Enter c to cancel. Desired Rating: --> ");
rateChoice = USER_INPUT.nextLine().trim();
if (rateChoice.equalsIgnoreCase("c")) {
return;
}
// Validate Entry...
if (!rateChoice.matches("[1-5]")) {
println("Invalid Entry (" + rateChoice + ")! Try again..." + LS);
rateChoice = "";
}
}
int rating = Integer.valueOf(rateChoice);
java.util.List<Properties> p = prop.getPropertiesByRating(rating);
if (p.isEmpty()) {
println("No accomodation available with the rating of " + rating + "!" + LS);
return;
}
String str = "Available accomodation with a rating of '" + rating + "':";
println(LS + str);
println(String.join("", java.util.Collections.nCopies(str.length(), "-")));
int cntr = 0;
for (Properties pp : p) {
cntr++;
println(pp.toStringTable(pp, cntr == 1));
}
println(line + LS);
}
private void rateAnAccomodation() {
/* Displayed ratings are always the AVERAGE of all ratings
provided for that particular propety. This is done within
the 'Properties.addRating()' method. For this reason and
for other obvious reasons the Properties List should be
saved to either a file or a database. If this is not done
then all added or modified data will be lost when the
application closes. The Properties List data should NOT
be hard-coded. It should be loaded in when the application
starts and saved to storage when data is added or modified.
*/
String[] pNames = prop.getAllPropertyNames();
String nameToRate = "";
while (nameToRate.isEmpty()) {
println(LS + "Enter the name of the accomodation you want to rate:");
print( "Enter 'c' to cancel. Rating: --> ");
nameToRate = USER_INPUT.nextLine().trim();
if (nameToRate.equalsIgnoreCase("c")) {
return;
}
// Validate Entry............................
if (nameToRate.isEmpty()) {
println("Invalid Entry! You must enter a Name! Try again...");
nameToRate = "";
continue;
}
// Does the name exist in List?
boolean found = false;
for (String name : pNames) {
if (name.equalsIgnoreCase(nameToRate)) {
// Yes it does...
found = true;
break; // Break out of this loop.
}
}
if (!found) {
println("Invalid Entry (" + nameToRate + ")!" + LS
+ "Can not find the name supplied! Try again..." + LS);
nameToRate = "";
}
}
//.................................................
/* If we get to here then the name supplied
(regarless of letter case) is in the List. */
String rateNum = "";
while (rateNum.isEmpty()) {
println();
print("Enter your rating (1 to 5 or 'c' to cancel): --> ");
rateNum = USER_INPUT.nextLine().trim();
if (rateNum.equalsIgnoreCase("c")) {
return;
}
// Validate Entry...
if (!rateNum.matches("[1-5]")) {
println("Invalid Entry (" + rateNum + ")! Try again..." + LS);
rateNum = "";
}
println();
}
// Set the rating.
int rating = Integer.valueOf(rateNum);
for (Properties p : prop.getProperties()) {
if (p.getPropertyName().equalsIgnoreCase(nameToRate)) {
int avgRating = p.getAverageRating();
p.addRating(rating);
println("Your rating of " + rating + " has been added to the accomodation" + LS
+ "named '" + nameToRate + "' which has moved its overall rating" + LS
+ "average from " + avgRating + " to an overall average rating of " +
p.getAverageRating() + "." + LS + "This is based on " +
p.getTotalNumberOfRatingsDone() + " rating(s) on the accomodation." + LS);
}
}
}
public static void println(Object... obj) {
if (obj.length > 0) {
System.out.println(obj[0]);
}
else {
System.out.println();
}
}
public static void printErr(Object... obj) {
if (obj.length > 0) {
System.err.println(obj[0]);
}
else {
System.err.println();
}
}
public static void print(Object... obj) {
if (obj.length > 0) {
System.out.print(obj[0]);
}
else {
System.out.print("");
}
}
}
The Properties class:
public class Properties {
public static java.util.List<Properties> properties = new java.util.ArrayList<>();
private String propertyName;
private String accomodationType;
private String description;
private String location;
private double pricePerDay;
private int averageRating = 0;
private int totalNumberOfRatings;
private boolean available;
// Constructor #1
public Properties() { }
// Constructor #2
public Properties(String propertyName, String accomodationType, String description,
String location, double pricePerDay, boolean available) {
this.propertyName = propertyName;
this.accomodationType = accomodationType;
this.description = description;
this.location = location;
this.pricePerDay = pricePerDay;
this.available = available;
}
// Getters & Setters
public java.util.List<Properties> getProperties() {
return properties;
}
public String getPropertyName() {
return propertyName;
}
public void setPropertyName(String propertyName) {
this.propertyName = propertyName;
}
public String getAccomodationType() {
return accomodationType;
}
public void setAccomodationType(String accomodationType) {
this.accomodationType = accomodationType;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public double getPricePerDay() {
return pricePerDay;
}
public void setPricePerDay(double pricePerDay) {
this.pricePerDay = pricePerDay;
}
public int getAverageRating() {
return this.averageRating;
}
public void addRating(int rating) {
// Rateing is an integer value from 1 to 5.
// Where 1 is Bad and 5 Excellent.
if (rating < 1) { rating = 1; }
else if (rating > 5) { rating = 5; }
int sum = 0, r = 0;
for (Properties p : properties) {
if (p.propertyName.equalsIgnoreCase(this.propertyName)) {
r++;
sum += rating;
}
}
if (sum > 0 && r > 0) {
this.averageRating = sum / r;
}
else {
this.averageRating = rating;
}
this.totalNumberOfRatings++;
}
public boolean isAvailable() {
return available;
}
public void setAvailable(boolean available) {
this.available = available;
}
#Override
public String toString() {
return propertyName + ", " + accomodationType + ", " + description + ", "
+ location + ", " + pricePerDay + ", " + averageRating + ", "
+ available;
}
public String toStringTable(Properties p, boolean... addHeader) {
boolean applyHeader = false;
if (addHeader.length > 0) {
applyHeader = addHeader[0];
}
String symbol = java.util.Currency.getInstance(java.util.Locale.getDefault()).getSymbol();
String header = "", underline = "", ls = System.lineSeparator();
StringBuilder sb = new StringBuilder("");
header = String.format("%-18s %-10s %-50s %-10s %-10s %-8s %-6s%n", "BNB Name",
"BNB Type", "BNB Description", "Location", "Price/Day", "Rating", "Avail.");
underline = String.join("", java.util.Collections.nCopies(header.length(), "=")) + ls;
if (applyHeader) {
sb.append(header).append(underline);
}
String[] desc = p.description.split("\\s+");
java.util.List<String> descTmp = new java.util.ArrayList<>();
StringBuilder sb2 = new StringBuilder("");
for (String str : desc) {
if ((sb2.toString() + " " + str).length() > 50) {
descTmp.add(sb2.toString());
sb2.setLength(0);
}
if (!sb2.toString().isEmpty()) {
sb2.append(" ");
}
sb2.append(str);
}
if (!sb2.toString().isEmpty()) {
descTmp.add(sb2.toString());
}
sb.append(String.format("%-18s %-10s %-50s %-12s " + symbol + "%-10.2f %-7s %-6s",
p.propertyName, p.accomodationType, descTmp.get(0), p.location,
p.pricePerDay, p.averageRating, (p.available ? "Yes" : "No")));
if (descTmp.size() > 1) {
for (int i = 1; i < descTmp.size(); i++) {
sb.append(ls).append(String.format("%-18s %-10s %-50s %-12s %-10s %-7s %-6s",
" "," ", descTmp.get(i), " ", " ", " ", " "));
}
}
return sb.toString();
}
public String[] getAllPropertyNames() {
java.util.List<String> tmp = new java.util.ArrayList<>();
for (Properties prop : properties) {
// Make sure names retrieved are Unique (DISTINCT)
if (!tmp.contains(prop.propertyName)) {
tmp.add(prop.propertyName);
}
}
return tmp.toArray(new String[tmp.size()]);
}
public String[] getAllAccomodationTypes() {
java.util.List<String> tmp = new java.util.ArrayList<>();
for (Properties prop : properties) {
// Make sure accomodations retrieved are Unique (DISTINCT)
if (!tmp.contains(prop.accomodationType)) {
tmp.add(prop.accomodationType);
}
}
return tmp.toArray(new String[tmp.size()]);
}
public java.util.List<Properties> getPropertiesByLocation(String location) {
java.util.List<Properties> tmp = new java.util.ArrayList<>();
for (Properties p : Properties.properties) {
if (p.location.equalsIgnoreCase(location) && !tmp.contains(p)) {
tmp.add(p);
}
}
return tmp;
}
public java.util.List<Properties> getPropertiesByAccomodationType(String accomodationType) {
java.util.List<Properties> tmp = new java.util.ArrayList<>();
for (Properties p : Properties.properties) {
if (p.accomodationType.equalsIgnoreCase(accomodationType) && !tmp.contains(p)) {
tmp.add(p);
}
}
return tmp;
}
public java.util.List<Properties> getPropertiesByRating(int rating) {
java.util.List<Properties> tmp = new java.util.ArrayList<>();
for (Properties p : Properties.properties) {
if (p.averageRating == rating && !tmp.contains(p)) {
tmp.add(p);
}
}
return tmp;
}
public int getTotalNumberOfRatingsDone() {
return this.totalNumberOfRatings;
}
public String[] getAllDescriptions() {
java.util.List<String> tmp = new java.util.ArrayList<>();
for (Properties prop : properties) {
// Make sure descriptions retrieved are Unique (DISTINCT)
if (!tmp.contains(prop.description)) {
tmp.add(prop.description);
}
}
return tmp.toArray(new String[tmp.size()]);
}
public String[] getAllLocations() {
java.util.List<String> tmp = new java.util.ArrayList<>();
for (Properties prop : properties) {
// Make sure locations retrieved are Unique (DISTINCT)
if (!tmp.contains(prop.location)) {
tmp.add(prop.location);
}
}
return tmp.toArray(new String[tmp.size()]);
}
public double[] getAllPerDayPrices() {
java.util.List<Double> tmp = new java.util.ArrayList<>();
for (Properties prop : properties) {
// Make sure locations retrieved are Unique (DISTINCT)
if (!tmp.contains(prop.pricePerDay)) {
tmp.add(prop.pricePerDay);
}
}
// Convert List<Double> to double[]...
double[] prices = new double[tmp.size()];
for (int i = 0; i < tmp.size(); i++) {
prices[i] = tmp.get(i);
}
return prices;
}
}
I am a beginner in Java, and I've been creating a practicing project for a game. For this purpose, I've already put some features in this project, and I separate the entire project into three files: Nimsys, NimPlayer, NimGame.
I've created these features.
addplayer into playerList in the NimPlayer.
removeplayer
editplayer
Now, I want two of the players to join the game, and do the following:
Score record
The times the player has played.
What I did was trying to store the user data (addplayer) from the prompt input, and brought the game to be played (last part of the incomplete code).
import java.util.Scanner;
public class Nimsys {
public static String[] splitName(String inName) {
String[] splittedLine = inName.split(",");
String[] name = null;
if (splittedLine.length==3) {
String userName = splittedLine[0].trim();
String familyName = splittedLine[1].trim();
String givenName = splittedLine[2].trim();
name = new String[3];
name[0] = userName;
name[1] = familyName;
name[2] = givenName;
}
return name;
}
public static String [] splitData(String dataIn) {
String[] splittedLine = dataIn.split(",");
String[] data = null;
if (splittedLine.length==4) {
String initialStone = splittedLine[0];
String stoneRemoval = splittedLine[1];
String player1 = splittedLine[2].trim();
String player2 = splittedLine[3].trim();
data = new String[4];
data[0] = initialStone;
data[1] = stoneRemoval;
data[2] = player1;
data[3] = player2;
}
return data;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true) {
System.out.print('$');
String commandin = in.next();
if (commandin.equals("addplayer")) {
String inName = in.nextLine();
String[] name = splitName(inName);
//Make sure the vadality of in name
if (name!=null && name.length==3) {
for (int i = 0; i < NimPlayer.getId(); i ++) {
String userCheck = NimPlayer.getPlayer()[i].getUserName();
if (userCheck.contains(name[0])) {
System.out.println("The player already exist");//Test if player has been created
}
}
NimPlayer.createPlayer(name[0], name[1], name[2]);
System.out.println("The player has been created.");
} else {
System.out.println("Not Valid! Please enter again!");
}
}
if (commandin.equals("removeplayer")) {
//cannot loop through the entire null array, would be NullPointerException
String removeUserName = in.nextLine().trim();
/*System.out.println("Are you sure you want to remove all players? (y/n) \n");
//System.out.print('$');
commandin = in.next();
if (commandin.equals("y")) {
for (int i = 0; i < NimPlayer.getId(); i++) {
NimPlayer.getPlayer()[i] = null;
System.out.println("Remove all the players");
}
} else {
System.out.print('$');
}*/
//commandin = in.next();
for (int i = 0; i < NimPlayer.getId(); i++) {
String userName = NimPlayer.getPlayer()[i].getUserName().trim();
if (removeUserName != null && userName.equals(removeUserName)) {
NimPlayer.getPlayer()[i] = null;
System.out.println("Remove successfully!");// A test to see if the code runs
} else {
System.out.println("The player does not exist");
}
}
}
if (commandin.equals("editplayer")) {
String inName = in.nextLine();
String[] splittedLine = inName.split(",");
if (splittedLine!=null && splittedLine.length==3) {
String userName = splittedLine[0].trim();
String familyName = splittedLine[1].trim();
String givenName = splittedLine[2].trim();
//System.out.println(userName+","+familyName+","+givenName);//Test if in name in the if loop
for (int i = 0; i < NimPlayer.getId(); i++) {
String userCheck = NimPlayer.getPlayer()[i].getUserName().trim();
if (userName != null && userCheck.equals(userName)) {
NimPlayer.getPlayer()[i].setFamilyName(familyName);
NimPlayer.getPlayer()[i].setGivenName(givenName);
System.out.println("Edit successfully");
} else {
System.out.println("The player does not exist.");
}
}
} else {
System.out.println("Invalid in! Please enter again.");
}
}
if (commandin.equals("displayplayer")) {
for (int i = 0; i < NimPlayer.getId(); i++) {
String userName = NimPlayer.getPlayer()[i].getUserName();
String familyName = NimPlayer.getPlayer()[i].getfamilyName();
String givenName = NimPlayer.getPlayer()[i].getGivenName();
System.out.println(userName+","+familyName+""+givenName);
}
}
if (commandin.equals("startgame")) {
String dataIn = in.nextLine();
String [] data = splitData(dataIn);
//Check if player in the array
if (data.length==4 && data !=null) {
for (int i = 0; i < NimPlayer.getId(); i++) {
for (int j = i + 1; j < NimPlayer.getId(); j++) {
String player1 = NimPlayer.getPlayer()[i].getUserName();
String player2 = NimPlayer.getPlayer()[j].getUserName();
if (player1==null || player2==null) {
System.out.println("One of the players does not exist. Please enter again");
} else {
System.out.println("Data built successfully.Game starts!");
break;
}
}
}
dataIn = in.nextLine();
}
int dataStone = Integer.parseInt(data[0]);
int dataRemoval = Integer.parseInt(data[1]);
}
}}
//username, given name, family name, number of game played, number of games won
public class NimPlayer {
private String userName;
private String familyName;
private String givenName;
static NimPlayer[] playerList = new NimPlayer[10]; // set an array here
static int id;
//define NimPlayer data type
public NimPlayer(String userName,String surName, String givenName) {
this.userName = userName;
this.familyName = surName;
this.givenName = givenName;
}
// create new data using NimPlayer data type
public static void createPlayer(String userName, String familyName, String givenName) {
if (id<10) {
playerList[id++] = new NimPlayer(userName, familyName, givenName);
} else {
System.out.println("Cannot add more players.");
}
}
public static int getId() {
return id;
}
public static NimPlayer [] getPlayer() {
return playerList;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public String getUserName() {
return userName;
}
public String getfamilyName() {
return familyName;
}
public String getGivenName() {
return givenName;
}
}
Above are my Nimsys and NimPlayers class. So far, I have a question:
Is it wrong to manipulate the players in the Nimplayer?
Or it is better to create an object in Nimsys if I want to store the record and the times game played?
public class NimGame {
int stoneBalance;
int stars;
public int initializeStone(int startStones) {
stoneBalance = startStones;
return stoneBalance;
}
public void removeStones(int stonesTaken) {
int updatedBalance = stoneBalance - stonesTaken;
stoneBalance = updatedBalance;
}
public void printStar(int star) {
stars = star;
stars = stoneBalance;
for (int stars = 1; stars <= star; stars++) {
System.out.print(" *");
}
System.out.println();
}
Scanner in = new Scanner(System.in);
String playOrNot;
do {
System.out.println("Initial stone count: "+datastone);
System.out.println("Maximum stone removal: "+dataRemoval);
System.out.println("Player 1: "+player1.getUserName());
System.out.println("Player 2: "+player2.getUserName());
// while stoneBalance > 0, two players keep playing the game
while (stoneBalance > 0) {
System.out.print(initialStone + " stones left:");
printStar(initialStone);
// player1's turn and remove the stones; decision of winning
System.out.println(player1 + "'s turn - remove how many?\n");
int takeStone = in.nextInt();
while (takeStone > dataRemoval || takeStone <= 0) {
System.out.println(
"Invalid, you need to remove stones under upper "+
"bound limit or above 0. \n Please enter again.");
takeStone = in.nextInt();
}
removeStones(takeStone); //remove the stone
if (stoneBalance > 0) {
//show the remaining stones
System.out.print(stoneBalance + " stones left:");
printStar(stoneBalance);
} else if (stoneBalance <= 0) {
System.out.println("Game Over\n" + player2 + " wins!\n");
break;
}
// player2's turn and remove the stones; decision of winning
System.out.println(player2 + "'s turn - remove how many?\n");
takeStone = in.nextInt();
while (takeStone > dataRemoval || takeStone <= 0) {
System.out.println(
"Invalid, you need to remove stones under upper " +
"bound limit or above 0. \n Please enter again.");
takeStone = in.nextInt();
}
removeStones(takeStone);
if (stoneBalance > 0) {
System.out.print(stoneBalance + " stones left:");
printStar(stoneBalance);
} else if (stoneBalance <= 0) {
System.out.println("Game Over\n" + player1 + " wins!\n");
break;
}
}
// ask players to play again
in.nextLine();
System.out.println("Do you want to play again (Y/N):");
playOrNot = in.nextLine();
} while (playOrNot.equals("Y"));
}
And this above is my NimGame class. It's the process of the classical Nim game. What should I do to introduce the player? What I did in Nimsys is only to check if players are inside the playerList.
Thanks for taking the time to review my code. Any help is highly appreciated!
On a side note (because it won't affect the execution of the program), the name of an identifier should be self-explanatory e.g. your getPlayer method should be named as getPlayerList as it is returning the playerList, not a single player.
Your logic for startgame should be as follows:
if (commandin.equals("startgame")) {
String dataIn = null, player1 = null, player2 = null;
do {
dataIn = in.nextLine();
String [] data = splitData(dataIn);
//Check if player in the array
if (data !=null && data.length==4) {
NimPlayer[] players = NimPlayer.getPlayerList();
for (int i = 0; i < players.length; i++) {
if(players[i].getUserName().equals(data[2])) {// Checking player1
player1 = players[i].getUserName();
break;
}
}
for (int i = 0; i < players.length; i++) {
if(players[i].getUserName().equals(data[3])) {// Checking player2
player2 = players[i].getUserName();
break;
}
}
}
} while(player1 == null || player2 == null)
//...
}
You can put the repeated code in a function to make your program modular e.g.
String findPlayerByName(String name){
String player = null;
NimPlayer[] players = NimPlayer.getPlayerList();
for (int i = 0; i < players.length; i++) {
if(players[i].getUserName().equals(name)) {
player = players[i].getUserName();
break;
}
}
return player;
}
Then, the logic for startgame will reduce to:
if (commandin.equals("startgame")) {
String dataIn = null, player1 = null, player2 = null;
do {
dataIn = in.nextLine();
String [] data = splitData(dataIn);
//Check if player in the array
if (data !=null && data.length==4) {
player1 = findPlayerByName(data[2]);
player2 = findPlayerByName(data[3]);
}
} while(player1 == null || player2 == null)
//...
}
Another thing I would like you to understand is the problem with the following line:
if (data.length==4 && data !=null)
It should be
if (data !=null && data.length==4)
This way, if data is null, the condition, data.length==4 will not be checked because && operator allows to proceed further only if the condition on its left side evaluates to true.
The problem with your line is that if data is null, you will get the NullPointerException because you will be checking .length on a null reference.
Now, I want two of the players to join the game, and do the following:
Score record
The times the player has played.
Currently, you have userName, familyName, and givenName attributes in NimPlayer class. You need to create two more attributes, private int score and private int numbersOfGamesPlayed with their public getters and setters. You need to use these attributes to store the value of score and the numbers of time a player has played the game.
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) + "]"
}
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());
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