Hello and thank you for your time in advanced.
I am trying to create a few different football leagues (e.g. the Italian national league (Serie A ), the English national league (Premier league), ... , second division Italian league (Serie B), etc).
Right now I'm trying to figure out what's the best way to separate clubs of different country's so that a Italian club cant compete in a Spanish league and vice versa.
As of now I have created the Player, PlayerBuilder, Team and TeamBuilder classes.
public class FootBallClub {
private String name;
private String stadium;
private String mainCoach;
private String secondCoach;
private ArrayList<FootballPlayer> playerList;
private ArrayList Matches;
private String county;
private int gamesPlayed;
private int gamesWon;
private int gamesDrawn;
private int gamesLost;
private int goalsScored;
private int goalsConceded;
private FootballPlayer topGoalScorer;
public FootBallClub() {
}
public void addPlayer(FootballPlayer player) {
playerList.add(player);
}
public void addPlayers (ArrayList<FootballPlayer> players) {
for (FootballPlayer player: players){
playerList.add(player);
}
}
public ArrayList<FootballPlayer> getPlayerList() {
ArrayList<FootballPlayer> players = new ArrayList<>();
for (FootballPlayer player : players) {
try {
players.add(player.clone());
} catch (CloneNotSupportedException e) {
System.out.println("Football Player " + player.getName() + " could not be cloned");
System.out.println(e.getStackTrace());
}
}
return players;
}
// getters and setters for all the fields
public static ArrayList<FootballPlayer> createTeam(){
String first = "Liam,Noah,Oliver,Elijah,William,James,Benjamin,Lucas,Henry,Alexander,Mason,Michael,Ethan,Daniel,Jacob,Logan,Jackson,Levi,Sebastian,Mateo,Jack,Owen,Theodore,Aiden,Samuel,Joseph,John,David,Wyatt,Matthew,Luke,Asher,Carter,Julian,Grayson,Leo,Jayden,Gabriel,Isaac,Lincoln,Anthony,Hudson,Dylan,Ezra,Thomas";
String [] firstNames = first.split(",");
String last = "Smith,Johnson,Williams,Brown,Jones,Garcia,Miller,Davis,Rodriguez,Martinez,Hernandez,Lopez,Gonzalez,Wilson,Anderson,Thomas,Taylor,Moore,Jackson,Martin,Lee,Perez,Thompson,White,Harris,Sanchez,Clark,Ramirez,Lewis,Robinson,Walker,Young,Allen,King,Wright,Scott,Torres,Nguyen,Hill,Flores,Green,Adams,Nelson,Baker,Hall,Rivera,Campbell,Mitchell,Carter,Roberts,Gomez,Phillips,Evans,Turner,Diaz,Parker,Cruz,Edwards,Collins,Reyes,Stewart,Morris,Morales,Murphy,Cook,Rogers,Gutierrez,Ortiz,Morgan,Cooper,Peterson,Bailey,Reed,Kelly,Howard,Ramos,Kim,Cox,Ward,Richardson,Watson,Brooks,Chavez,Wood,James,Bennett,Gray,Mendoza,Ruiz,Hughes,Price,Alvarez,Castillo,Sanders,Patel,Myers,Long,Ross,Foster,Jimenez,Powell,Jenkins,Perry,Russell,Sullivan,Bell,Coleman,Butler,Henderson,Barnes,Gonzales,Fisher,Vasquez,Simmons,Romero,Jordan,Patterson,Alexander,Hamilton,Graham,Reynolds,Griffin,Wallace,Moreno,West,Cole,Hayes,Bryant,Herrera,Gibson,Ellis,Tran,Medina,Aguilar,Stevens,Murray,Ford,Castro,Marshall,Owens,Harrison,Fernandez,Mcdonald,Woods,Washington,Kennedy,Wells,Vargas,Henry,Chen,Freeman,Webb,Tucker,Guzman,Burns,Crawford,Olson,Simpson,Porter,Hunter,Gordon,Mendez,Silva,Shaw,Snyder,Mason,Dixon,Munoz,Hunt,Hicks,Holmes,Palmer,Wagner,Black,Robertson,Boyd,Rose,Stone,Salazar,Fox,Warren,Mills,Meyer,Rice,Schmidt,Garza,Daniels";
String [] lastNames = last.split(",");
Random random = new Random();
final List<FootballPosition> footballPositions = Collections.unmodifiableList(Arrays.asList(FootballPosition.values()));
final List<DominantSide> sides = Collections.unmodifiableList(Arrays.asList(DominantSide.values()));
ArrayList<FootballPlayer> footballPlayers = new ArrayList<FootballPlayer>();
for (int i =0; i<footballPositions.size() ; i++) {
String randomeName = firstNames[random.nextInt(1000)]+ " "+ lastNames[random.nextInt(1000)];
int randomAge = 18 + random.nextInt(23);
int randomHeight = 165 + random.nextInt(30);
int randomWeight = (int) ((randomHeight - 100) * 0.85 + random.nextInt(25));
DominantSide randomSide = sides.get(random.nextInt(3));
boolean isHealthy = true;
int randomSalary = 700000 + random.nextInt(5000000);
FootballPosition primaryPosition = footballPositions.get(i);
List<FootballPosition> allPosition = new ArrayList<FootballPosition>();
allPosition.add(primaryPosition);
EnumSet set = EnumSet.noneOf(FootballPosition.class);
for (int j = 0; j < random.nextInt(4); j++) {
FootballPosition newPosition = footballPositions.get(random.nextInt(footballPositions.size()));
if(allPosition.contains(newPosition)){
i--;
}
set.add(newPosition);
}
FootballPlayer randomPlayer = new FootballPlayerBuilder()
.setName(randomeName)
.setAge(randomAge)
.setHeight(randomHeight)
.setWeight(randomWeight)
.setDominantSide(randomSide)
.setIsHealthy(isHealthy)
.setSalary(randomSalary)
.setPrimaryPosition(primaryPosition)
.setSecondaryPositions(set)
.build();
footballPlayers.add(randomPlayer);
}
return footballPlayers;
}
}
public class FootballPlayer {
private String name;
private FootballPosition primaryPosition;
private EnumSet<FootballPosition> secondaryPositions;
private double height;
private double weight;
private int age;
private Enum dominantSide;
private boolean isHealthy;
private int salary;
public FootballPlayer() {
}
// getters and setters for all the fields
#Override
public String toString() {
return "FootballPlayer{" +
"name='" + name + '\'' +
", primaryPosition=" + primaryPosition +
", secondaryPositions=" + secondaryPositions +
", height=" + height +
", weight=" + weight +
", age=" + age +
", dominantSide=" + dominantSide +
", isHealthy=" + isHealthy +
", salary=" + salary +
'}';
}
#Override
public FootballPlayer clone() throws CloneNotSupportedException {
FootballPlayer clone = new FootballPlayerBuilder()
.setName(this.name)
.setAge(this.age)
.setHeight((int) this.height)
.setWeight((int) this.weight)
.setDominantSide(this.dominantSide)
.setIsHealthy(this.isHealthy)
.setSalary(this.salary)
.setPrimaryPosition(this.primaryPosition)
.setSecondaryPositions(this.secondaryPositions)
.build();
return clone;
}
}
Player and Team simply hold information about the player and team through their field and the builders build the objects.
None of the classes implement or extend any classes.
My question is : What's the best way implementing the League class so that a league from a certain county only accepts teams form the same country.
Should I save a string, int, enum ..., on the team class and check before adding to the league table? Is the a clever way to use interfaces to salve this problem?
Consider making an enum, it is definitely better than a generic string:
enum Country {
Spain,
Germany,
UK
}
Each league may contain a HashSet<FootBallClub>. So, you can put football clubs into leagues as you want.
First off I know this probably isn't the most sophisticated way to do what I want, but its the way I thought of.
I am attempting to load in Soccer/Football data into an array list then create commands to let me analyze it.
Like if I want to know the last couple fo scores between two teams, or how many goals a team has scored in some seasons.
I have a file (6.txt) with my data delimited by ,
Ex. "12/8/17","Alaves","Las Palmas",2,0,'H',22,6,9,1
I have a contractor that takes in arguments
Then I have an array list for each team with their data
import java.util.ArrayList;
import java.util.Scanner;
import java.io.*;
public class games {
String hTeam;
String date;
String aTeam;
int totGoals;
int hGoals, aGoals, result, points, wins, draws, losses, hShots, aShots, hShotsTarget, aShotsTarget;
public games(String date, String hTeam, String aTeam, int hGoals, int aGoals, char result, int hShots, int aShots, int hShotsTarget, int aShotsTarget) {
this.hTeam = hTeam;
this.aTeam = aTeam;
this.hGoals = hGoals;
this.aGoals = aGoals;
this.result = result;
this.hShots = hShots;
this.aShots = aShots;
this.date = date;
}
public String toString() {
String temp = "";
String result = "";
if (this.result == 'H') {
result += "won against";
}
else if(this.result == 'A') {
result += "lost to";
}
else if (this.result == 'D') {
result += "drew with";
}
temp += "On " + date + " " + hTeam + " " + result + " " + aTeam + " " + hGoals + " to " + aGoals + "\n";
return temp;
}
public static void main(String[] args) {
ArrayList<games> Alaves = new ArrayList<games>();
Scanner s = new Scanner(new File("6.txt"));
while (s.hasNext()) {
Alaves.add(new games(s.nextLine()));
}
}
}
I want to be able to create an array list for each team with an associated file that will fill that list.
My end goal, is to be able to compare two teams using this data, which team is more likely to win, well lets check head to head matches and goals scored etc.
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'm writing a program with two classes, one person class and one main. The person class use get and set for six people and then the main class ask for the names and then show the user the six names (in my example it only shows four). Is it possible to use a loop for this? I know I could use a list for this but it's for school and they want us to use constructors, set and get in the first week or so. The code now looks like this. Is this even possible with an example like this or do I need to use a list or an array?
PersonClass.java
public class PersonClass {
private String namn;
public void setNamn(String namn) {
this.namn = namn;
}
public String getNamn() {
return namn;
}
}
MainClass.java
import javax.swing.*;
public class MainClass {
public static void main(String[] args) {
PersonClass person1 = new PersonClass();
PersonClass person2 = new PersonClass();
PersonClass person3 = new PersonClass();
PersonClass person4 = new PersonClass();
String namn1 = JOptionPane.showInputDialog("Enter full name for person 1!");
person1.setNamn(namn1);
String namn2 = JOptionPane.showInputDialog("Enter full name for person 2!");
person2.setNamn(namn2);
String namn3 = JOptionPane.showInputDialog("Enter full name for person 3!");
person3.setNamn(namn3);
String namn4 = JOptionPane.showInputDialog("Enter full name for person 4!");
person3.setNamn(namn4);
JOptionPane.showMessageDialog(null, "Person 1: " + person1.getNamn() +
"\nPerson 2: " + person2.getNamn() + "\nPerson 3: " + person3.getNamn() +
"\nPerson 4: " + person4.getNamn());
}
}
I'm personally a fan of Lists as well, but Arrays are just as good of an option. I build the output as it goes with a little String.format help.
List<PersonClass> persons = new ArrayList<PersonClass>();
String output = "";
for(int i = 1; i <= 6; i++) {
String name = JOptionPane.showInputDialog(String.format("Enter full name for person %d!", i));
PersonClass person = new PersonClass();
person.setNamn(name);
persons.add(person);
output += String.format("Person %d: %s\n",i, person.getNamn());
}
JOptionPane.showMessageDialog(null, output);
Hello because of your tone when suggesting arrays I take it that you are not comfortable with the concept yet, but maybe talk with your teacher about this and about the answers you get here!
PersonClass[] personArray = {person1, person2, person3, person4};
for (int i = 0; i < personArray.length; i++)
{
// (i + 1) because our array starts at 0, but it's the 0 + 1th person
String msg = "Enter full name for person" + (i + 1);
personArray[i].setName(JOptionPane.showInputDialog(msg));
}
List<PersonClass> people = new ArrayList<PersonClass>;
for (int i = 0; i < 6; i++) { // set i to number of required people
PersonClass person = new PersonClass();
person.setNamn(JOptionPane.showInputDialog("Enter full name for person " + (i + 1) +"!");
people.add(person);
JOptionPane.showMessageDialog(null, person.getNamn());
}
people will contain all the new PersonClass you created.
PersonClass[] persons = new PersonClass[4];
for(int i = 0; i < persons.length; i++){
persons[i] = new PersonClass();
persons[i].setNamn(JOptionPane.showInputDialog("Enter full name for person " + (i+1));
}
If dialog will be closed - there will be null returned.
One way to do this with a loop would be to make your main class like this. See comments:
import java.util.ArrayList;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
ArrayList<PersonClass> people = new ArrayList<PersonClass>();
int index=5;
//Loop that will ask for 6 names
for(int ii=0; ii<=index; ii++){
//create person object
PersonClass person = new PersonClass();
//get/set the name
person.setNamn(JOptionPane.showInputDialog("Enter full name for person " + ii + " !"));
//save name in arraylist
people.add(person);
}
int count = 1;
//will output names via a loop
for(PersonClass person : people){
if(person.getNamn() != null){
JOptionPane.showMessageDialog(null, "Person " + count + " name: " + person.getNamn());
}
count++;
}
}
}
If it were me, I'd create a custom constructor for the PersonClass, which sets the namn on construction:
public class PersonClass {
private String namn;
//Custom constructor using a setter
public PersonClass(String namn){
this.setNamn(namn);
}
public void setNamn(String namn) {
this.namn = namn;
}
public String getNamn() {
return namn;
}
}
Then I would do this in my MainClass:
import java.util.ArrayList;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
ArrayList<PersonClass> people = new ArrayList<PersonClass>();
int index=5;
//Loop that will ask for 6 names
for(int ii=0; ii<=index; ii++){
//create, set, and add name to list
people.add(new PersonClass(JOptionPane.showInputDialog("Enter full name for person " + ii + " !")));
}
int count = 1;
for(PersonClass person : people){
if(person.getNamn() != null){
JOptionPane.showMessageDialog(null, "Person " + count + " name: " + person.getNamn());
}
count++;
}
}
}