Hi Im trying to set up a person class for each player on a leaderboard, since i dont know how long the leader board is im going to try and loop the amount of people by the count of the rows in the leaderboard. Then im trying to "get" the points for each row and compare each one again the previous to assert the higher number is one the top, ive never used getters and setters before and cant seem to figure out how to do this, any help??
Here is the code for the information i want for each person, I need to find the player_picks, position and player_points . I then need to compare the count of each player_picks total with each player as i go down the leaderboard. If the pick_total is is equal i then need to compare their points total.Ive been trying this for a few weeks but someone suggested it would be easier making a player class and then using get and setters to assign attributes to each of them. SO i could then compare player1 with player 2, player 2 and player 3 etc. Whats making mit difficult is that i dont know the size of the list each time so its confusing me.
Below is the code im using which gives me the attributes im look to "set" but i dont know how to set up a "people" in a person class as the amount of people required each time with be changing (using int size) as a different amount of people join each game.
Im new to this so if im not explaining this well let me know.
public void test_player_leaderboard_entry() {
int size = playerRows.size();
for (int i = 0; i < size; i++) {
//Position
String position_first_player = Drivers.getDriver().findElement(By.cssSelector("[data-qa-position-value='" + i + "']")).getText();
//Points
String points_player = Drivers.getDriver().findElement(By.cssSelector("[data-qa-points-value='" + i + "']")).getText();
//Username
String username_player = Drivers.getDriver().findElement(By.cssSelector("[data-qa-player-value='" + i + "']")).getText();
//Row Number
Integer row = i + 1;
Integer total_of_won_and_looking_good = 0;
//PICKS
for (int pick_number = 1; pick_number < 5; pick_number++) {
String pick_status = Drivers.getDriver().findElement(By.xpath("//*[#id='root']/div/main/section[2]/section/div/ol/a[" + row + "]/li/div[3]/div[" + pick_number + "]/div")).getAttribute("data-qa-pick-state");
//System.out.println(pick_status);
if (Integer.parseInt(pick_status) == 2 || Integer.parseInt(pick_status) == 1) {
total_of_won_and_looking_good = total_of_won_and_looking_good + 1;
}
//System.out.println(total_of_won_and_looking_good);
}
//System.out.println("On row number " + row + " we find " + username_player + " in position " + position_first_player + " with " + total_of_won_and_looking_good + " correct picks and " + points_player + " points!");
}
}
First, you are not attempting to set up a person class for each player on a leaderboard, you are attempting to design a Person class and instantiate a Person object for each person row on the leaderboard. I would heavily suggest reading the Oracle Docs and learning more about classes and objects.
Within your loop you will want to create a new Person object, scrape the necessary value, call the appropriate setter with the value and add that player object to a collection. e.g.
Person p = new Person() //create new Person object
int points = Integer.parseInt(Drivers.getDriver().findElement(By.cssSelector("[data-qa-points-value='" + i + "']")).getText());
p.setPoints(points); //call setter for points field
personList.add(p); //add person to list
An example of a simple person class could look like the following. Note that implementing the Comparable interface allows for Person objects to be sorted when stored in a List or array as seen below.
public class Person implements Comparable<Person> {
private int score;
public Person() { }
public void setScore(int score) { this.score = score; }
public int getScore() { return this.score; }
public static void main(String[] args) {
Person p1 = new Person();
Person p2 = new Person();
p1.setScore(80);
p2.setScore(90);
List<Person> people = new ArrayList<>();
people.add(p1);
people.add(p2);
System.out.println("Before sorting: " + people.toString());
Collections.sort(people);
System.out.println("After sorting: " + people.toString());
}
#Override
public int compareTo(Person p) {
if (p.getScore() > this.score)
return 1;
if (p.getScore() < this.score)
return -1;
return 0;
}
public String toString() {
return String.format("Person -> score: %d", this.score);
}
}
Related
I have an assignment which I have to program that creates a standings table from match list input. I used the word "infinite" because input size is unknown so I have to create a program that works until there's no matches left. I created a football class for this(input contains 2 other sports and their own matches and teams indicating the sports type with first letter of the sport with "F, B, V" for example, they're only different in scoring part, so I though if I can make football work, I can make anything else work) that contains everything required in standings table, and methods for match results which looks like this:
public class Football {
private int scoredGoals;
private int receivedGoals;
private String teamName;
private int Score;
private int wins;
private int losses;
private int MatchCount;
private int draws;
public void teamValues(String teamName, int Sgoals, int Rgoals) {
this.teamName = teamName;
this.scoredGoals = Sgoals;
this.receivedGoals = Rgoals;
}
public void matched() {
MatchCount++;
}
public void winner() {
wins++;
}
public void draw() {
draws++;
}
public void loser() {
losses++;
}
public void winScore() {
Score += 3;
}
public void drawScore() {
Score += 1;
}
public String showTeams() {
return (teamName + " " + MatchCount + " " + wins + " " + draws + " " + losses + " " + scoredGoals+":"+receivedGoals + " " + Score);
}
}
And in main class I'm calling methods in if blocks to calculate wins, score, matches count etc. And main looks like this:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashSet;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("input.txt");
Scanner scan = new Scanner(file);
String fileString = "";
Football teams[] = new Football[2];
HashSet<String> teamsArray = new HashSet<String>();
while(scan.hasNextLine()) {
fileString = scan.nextLine();
String[] match = fileString.split("\\t|:");
if(match[0].equals("F")) {
int team1score = Integer.valueOf(match[3].trim());
int team2score = Integer.valueOf(match[4].trim());
teams[0] = new Football();
teams[0].teamValues(match[1], team1score, team2score);
teams[1] = new Football();
teams[1].teamValues(match[2], team2score, team1score);
teams[0].matched();
teams[1].matched();
if(team1score>team2score) {
teams[0].winner();
teams[1].loser();
teams[0].winScore();
}
if(team1score==team2score) {
teams[0].draw();
teams[1].draw();
teams[0].drawScore();
teams[1].drawScore();
}
if(team1score<team2score) {
teams[1].winner();
teams[0].loser();
teams[1].winScore();
}
String team0 = teams[0].showTeams();
String team1 = teams[1].showTeams();
teamsArray.add(team0);
teamsArray.add(team1);
}
}
scan.close();
}
}
Since the input is static, I used arrays to work around. My problem with my code is I cant find a way to store my teams without duplicates and the variables that comes within and update whenever that team has another match.
I tried;
Storing them in a 2D string array but since the amount of teams is unknown I think it won't be a healthy way to approach to the problem.
Storing them in a String[] array list, which ended up storing the adresses instead of the values of the teams.
Set which I still use to check if at least the methods are working as intended.
It feels like I hit the wall with this program and I need to start over, so any kind of advice is appreciated.
Here's an example of input and output:
Input:
Home Team Guest Team H : G
F Manchester U. Chelsea 2 : 2
F Liverpool Manchester City 3 : 2
F Leicester City Everton 1 : 3
V Team A Team B 3 : 0
F Tottenham Liverpool 3 : 1
B Team B Team A 90 : 96
F West Ham Manchester U. 2 : 1
F Arsenal Manchester City 0 : 2
F Chelsea Arsenal 3 : 3
Output:
Name Matches Wins Draw Lose Scored:Received Score
1. Manchester U. 10 6 2 2 27:22 20
2. Arsenal 10 6 2 2 25:24 20
3. Chelsea 10 5 3 2 28:20 18
4. Liverpool 10 4 4 2 22:19 16
5. Tottenham 10 4 4 2 22:21 16
There are teams with same scores, because calculating average of scored and received goals is another way to sort the teams.
First some changes to the Football class:
Override equals to be able to search the list
Override compareTo for sorting
Override toString instead of showTeams
Create a constructor
Combine most functions into teamValues
import java.util.Formatter;
public class Football implements Comparable<Football> {
private int scoredGoals;
private int receivedGoals;
private String teamName;
private int score;
private int wins;
private int losses;
private int draws;
private int matchCount;
public int compareTo(Football f) {
return score - f.score;
}
public boolean equals(Object o) {
if (o == null) {
return false;
}
else if (o instanceof Football) {
return teamName.equals(((Football)o).teamName);
}
else if (o instanceof String) {
return teamName.equals((String)o);
}
return false;
}
public Football(String teamName) {
this.teamName = teamName;
}
public void teamValues(int scoredGoals, int receivedGoals) {
this.scoredGoals += scoredGoals;
this.receivedGoals += receivedGoals;
matchCount++;
if (scoredGoals < receivedGoals) {
losses++;
}
else if (scoredGoals > receivedGoals) {
wins++;
score += 3;
}
else {
draws++;
score += 1;
}
}
public String toString() {
return new Formatter().format("%-20s %3d %3d %3d %3d %3d:%-3d %d",
teamName, matchCount, wins, draws, losses, scoredGoals, receivedGoals, score)
.toString();
}
}
For the main program, you don't want to create a new team every time - only when a team is first encountered in the file. Put all the teams in a List. When parsing a new game, first try to find the team in the list. If it is not in there, add it.
List<Football> teamsArray = new ArrayList<>();
while (scan.hasNextLine()) {
fileString = scan.nextLine();
String[]match = fileString.split("\\t|:");
if (match.length == 5 && match[0].equals("F")) {
int team1score = Integer.valueOf(match[3].trim());
int team2score = Integer.valueOf(match[4].trim());
// Create a temp team to search the List
Football team1 = new Football(match[1]);
// Search the list
if (!teamsArray.contains(team1)) {
// Not in the list already. Add it
teamsArray.add(team1);
}
else {
// Already in the List. Use that one.
team1 = teamsArray.get(teamsArray.indexOf(team1));
}
// Repeat for team 2
Football team2 = new Football(match[2]);
if (!teamsArray.contains(team2)) {
teamsArray.add(team2);
}
else {
team2 = teamsArray.get(teamsArray.indexOf(team2));
}
team1.teamValues(team1score, team2score);
team2.teamValues(team2score, team1score);
}
}
System.out.println("Name M W D L S:R S");
// Sort and print
teamsArray
.stream()
.sorted(Comparator.reverseOrder())
.forEach(t -> System.out.println(t));
I am learning Java on my own, i came a cross this interesting example and i found it difficult to understand it.
What i want to know is, what is this called in Java when you have several classes under the same package all of them are Overlapping. Please take a look at the example below ? Note that none of the classes use implements, interface, abstract, extends etc...
And is it possible to find more of these examples ?
class Flightplan
public class Flightplan {
String type;
int seat;
String from;
String to;
// Other local variables, style captain ...
Person[] passenger;
int counter = 0;
Flightplan (String t, int s, String startPlace, String d) {
type = t;
seat = s;
passenger = new Person [s-1]; // kapten tar ett säte
// Captain takes a seat
from = startPlace;
to = d;
}
void book (Person p, String f, String t) {
if (f.equals(from) && t.equals(to)) {
passenger[counter] = p;
to = t;
counter++;
}
else System.out.println(p.name + " try to book a wrong flight !");
}
void flyg() {
System.out.println("On the plane " + this.typ + " reser");
for (int i = 0; i < passenger.length && passenger[i] != null; i++) {
System.out.println(passenger[i].name + ", ");
}
System.out.println("\n");
from = to;
}
}
class Person
public class Person {
String name;
String from;
String to;
String stopover;
int bags;
Flightplan flight;
Person (String n, String f, String m, String t, int v) {
name = n;
from = f;
stopover = m; // Only one stopover is approved, otherwise we would enter this as an array
to = t;
bags = v;
}
void boardNextLeg(Flightplan plan) {
flight = plan;
// Function bar for a stopover due. if-kit building
if (!stopover.equals(null) && flight.from.equals(this.from) && flight.to.equals(this.stopover)) {
System.out.print(this.name + " is now in between");
System.out.println(from + " and " + stopover);
flight.book(this, from, stopover);
}
else if (flight.from.equals(this.from) && flight.to.equals(this.to)) {
System.out.println(from + " och " + to);
flight.book(this, from, to);
}
else System.out.println(this.name + " could not be booked on a flight");
}
}
What is this called in Java when you have
several classes under the same package all of them are Overlapping ?
This is NOT overlapping, rather this is called circular dependency because your Flightplan and Person are dependent on each other, which is bad design and poorly developed.
Basically Circular Dependencies cause lots of issues (like OutofMemoryError) if not properly used, so they should be avoided in between the classes/packages.
You can look here for more details on circular dependencies.
By overlapping you mean that they have member variables with the same names? Each class has a different list of member variables, and one class presents no restrictions to another class.
I think this is called "Several classes that each deal with similar data values"
This question already has answers here:
Having inheritance and polymorphism issues with Java
(2 answers)
Closed 6 years ago.
I am trying to output calclatefee of $2 per day after 3 days. I have switched things around and I am left at this which looks a little sloppy. This Array is also making me take the confusing way.
public class Movie {
String rating;
String title;
int id;
int rentTime;
public String setrating() {
return rating;
}
public void rating(String getrating) {
rating = getrating;
}
public int setid() {
return id;
}
public void id(int agetid) {
id = agetid;
}
public String settitle() {
return title;
}
public void title(String gettitle) {
title = gettitle;
}
public int setfees() {
return rentTime;
}
public void fees(int getrentTime) {
rentTime = getrentTime;
}
public Movie() {
title = " ";
rating = " ";
id = 0;
rentTime = 0;
System.out.println("default constructor");
}
public Movie(String title, String rating, int id, int rentTime) {
title = " not overridden ";
rating = " NR ";
id = 0;
rentTime = 0;
System.out.println("Overloaded -" + title + rating + id + rentTime);
}
public static void main(String[] args) {
Movie[] Array = {
new Action(" The 100", " pg-13", 105, 7, 3),
new Comedy(" Supernatural", " pg-13", 5, 2, 0),
new Drama(" Lost 2", " R", 9, 2, 0) };
for (int x = 0; x < Array.length; x++) {
// System.out.println(x);
System.out.println(Array[x].toString());
}
}
}
public abstract class Action extends Movie {
protected double latecost;
protected double latefees = 3;
public Action(String gettitle, String getrating, int getid, int getrentTime, double latecost) {
super(gettitle, getrating, getid, getrentTime);
title = gettitle;
rating = getrating;
id = getid;
rentTime = getrentTime;
latecost = latefees;
System.out.println("Overridden " + title + rating + " " + id + " " + " " + rentTime + " "
+ latecost);
}
public double calclatefees(double latecost, double rentTime) {
if (rentTime > 3)
latefees = ((rentTime - 3) * latecost);
return latefees;
}
#Override
public String toString() {
String x = "\nMovie: " + title + " is rated " + rating + "\nMovie ID number: " + id
+ " and the late fee for action movies is $" + latecost + "\n";
return x;
}
protected void finalize() throws Throwable {
try {
System.out.println("Finalize method");
} finally {
super.finalize();
}
}
public void dispose() {
System.out.println(" dispose method");
}
}
Problems:
There's no calclatefee method to override in the parent class. If you want a child class to override method, it must be present in the parent class, at least as an abstract method (if the parent is abstract or is an interface).
You never call your calclatefee method anywhere, so you shouldn't expect to ever see its result in your output.
Your child class, Action, is abstract -- isn't that backwards? Most often its the parent class that's abstract, so why are you structuring it this way? And as written your main method shouldn't compile since you seem to be trying to create an instance of an abstract class.
Your class overrides the finalize() method, something that is generally not recommended. Fortunately your override doesn't really do anything other than output to the standard out and then call the super's method, but still, why risk it?
Side issues
Your code does not follow Java naming conventions. Variable names should all begin with a lower letter while class names with an upper case letter. Learning this and following this will allow us to better understand your code, and would allow you to better understand the code of others.
You will want to try to improve the formatting of your code that you post in here and your code in general. Good formatting including using an indentation style that is uniform and consistent will help others (us!) to better understand your code, and more importantly, it will help you to better understand your code and thus fix your own bugs. Also it shows that you're willing to put in extra effort to make it easier for the volunteers here to help you, and that effort is much appreciated. I took the liberty of trying to fix this for you.
Ok so i made a car race script in java . It has two classes. The Car class and TheRace class.
The Car class just has stuff about the car like the distance the car has traveled, and in TheRace, I have two arrays for the drivers (driverArray) and sponsors (sponsors). I made a Car class array so each driver have different speeds and distance traveled.
Anyway, as you can see I made a boolean called winner, and a while loop that will keep going until the winner is true. The drivers distance becomes more and more in a while loop until myDistance is equal to or greater than 100.
In the code you can see that, if(carList[i].myDistance() >= 100){ winner = true;}, So then i display the Winner.
I have been trying to make it so it shows all the people who eventually cross the finish line 100 , and display them in the corrector order they finished. Like sorting an array or something. How i can show what place everyone got. How do i do this?
TheRace class,
package NASCAR;
import java.util.Arrays;
import java.util.Random;
public class TheRace {
// variables
public static String[] driverArray = {"steave smith", "Cheese farlin","Bob Joe","Josh Svioda", "Andrew Kralovec", "Ricky Bobby","Ashey GirslCanDriveTo","Kelsey IAgree","Joe ThisIsAManSport","Jess TheHellItIs","Jesus Defualt","Jason seglad","Andrew Smith","Andrew Johnson","Andrew Kosevsky","Andrew Anderson","Andrew Andrew", "Kate Andrew","Blondey Gold","Golden Blonde","Im Twenty" };
public static String[] sponsors = {"CocaCola","Pepsi","CoorsLight","GOD"} ;
public int[] currentDistance = new int[20];
public static void main(String[] args) {
Car[] carList = new Car[20] ;
Random rand = new Random();
for(int i =0 ; i < carList.length;i++){
carList[i] = new Car(driverArray[rand.nextInt(20)], sponsors[rand.nextInt(4)]) ;
} //end for
int lapCounter = 0 ;
boolean winner = false;
while(!winner){
for(int i = 0; i < carList.length; i++){
carList[i].changeDistance();
if(lapCounter % 6 == 0){
carList[i].speedChange();
} // end if change speed
System.out.println(carList[i].trackProgress());
if(carList[i].myDistance() >= 100){
winner = true;
System.out.println("_____ THE WINNER OF THE RACE IS: "+carList[i].myName()+" For team: "+carList[i].myTeam());
break ;
}
}// end for
lapCounter++;
System.out.println("---------------------------------");
} // end while
}// end main
}
Car class,
package NASCAR;
import java.util.Random;
public class Car {
//variables
private float totalOdMiles ;
private float speedPerHour ;
private String driverName ;
private String sponsorName ;
private Random rand = new Random();
public Car(String driverName, String sponsorName){
this.driverName = driverName ;
this.sponsorName = sponsorName ;
this.totalOdMiles = 0;
this.speedPerHour = rand.nextInt( 60);
}
public String myName(){
this.driverName = driverName;
return driverName ;
}
public String myTeam(){
this.sponsorName = sponsorName;
return sponsorName ;
}
public float myDistance(){ //reprot distance
return totalOdMiles;
}
public void speedChange(){ //ChangeSpeed()
this.speedPerHour = rand.nextInt(60);
}
public void changeDistance(){ //UpdateProgress()
float milesPerSecond = this.speedPerHour / 3600;
this.totalOdMiles+=milesPerSecond;
}
public String trackProgress(){ //ToString()
return this.driverName +" driving the "+ this.sponsorName+" car is going "+ this.totalOdMiles +"MPS "+this.totalOdMiles;
}
}
Ideally you should avoid the problem of having to sort two arrays simultaneously by adding the currentDistance field to the Car class. Then you can sort the carList using currentDistance.
For example, using java 8 you can get the first 3 places with:
Arrays.stream(carList)
.sorted((c1, c2) -> c2.currentDistance - c1.currentDistance)
.map(c -> c.getName())
.limit(3);
Hava a look at this custom Comparator,
put this code after your while loop,
Collections.sort(Arrays.asList(carList), new Comparator<Car>() {
#Override
public int compare(Car o1, Car o2) {
return Float.compare(o2.myDistance(), o1.myDistance());
}
});
to print the sorted names along with their rank,
for (Car s : carList){
System.out.println(s.myDistance() + " " + s.myName());
}
Output:
THE WINNER OF THE RACE IS: Andrew Johnson For team: CocaCola
100.004135 Andrew Johnson
99.623375 Jesus Defualt
99.23477 Andrew Smith
99.20563 Andrew Andrew
98.94183 Jesus Defualt
98.87631 Blondey Gold
98.86331 Jesus Defualt
98.64405 steave smith
98.54269 Jason seglad
98.24685 Bob Joe
98.23995 Andrew Kosevsky
98.06155 Ricky Bobby
97.81364 Jess TheHellItIs
97.77215 Blondey Gold
97.72567 Ashey GirslCanDriveTo
97.57001 Ashey GirslCanDriveTo
97.54619 Cheese farlin
97.29426 Andrew Kralovec
96.68102 Andrew Kosevsky
96.018654 Ashey GirslCanDriveTo
to list the first 5 places, use this instead,
for (int i=0; i<5; i++){
System.out.println(carList[i].myDistance() + " " + carList[i].myName() + ", -- Rank: " + (i+1));
}
This could be done more easily if you are using Java 8,
Arrays.stream(carList)
.sorted((a, b) -> Float.compare(b.myDistance(), a.myDistance()))
.map(c -> c.myDistance() + " " + c.myName())
.forEachOrdered(System.out::println);
This will get you the ranks of all the drivers in descending order along with their respective speed.
I propose an easy solution based on what I think you're asking.
Simply create a new array, carPlace[] (as an example) and add carList[i] to that array as soon as they finish.
That way 1st place will be carPlace[0], 2nd place carPlace[1] etc.
Once all cars are placed, then you can break out of the while loop as before.
You may not want to have your loop break as soon as a winner is found though - as this method requires all cars being added to the array.
If this is not what you are asking please specify ...
Happy coding!
your car class could imlpement the Comparable interface :
public class Car implements Comparable<Car>
#Override
public int compareTo(Car o) {
return this.totalOdMiles < o.totalOdMiles ? 0 : 1;
}
and the you can sort your array at the end of your while:
Arrays.sort(carList);
this should somehow work i guess :)
Im working on an Digital Technology assessment. It's a Program to store a customers Pizzas, Extras and information at a Pizza store. In my confirmation window, I need to print all the pizzas he is ordering. Here are my hashmaps:
private HashMap<Integer, String> pizzas = new HashMap<Integer, String>();
private HashMap<String, Integer> pizzas_count = new HashMap<String, Integer>();
And my addPizza method, aswell as my getOrder method
public void addPizza(String name){
if(pizzas.containsValue(name)){
int count = pizzas_count.get(name);
pizzas_count.remove(name);
pizzas_count.put(name, count++);
}else{
pizzas.put(pizzas.size(), name);
pizzas_count.put(name, 1);
}
}
public String getOrder(){
String order = "";
System.out.println(pizzas.toString());
int i;
for(i = 0; i < 12; i++){
if(pizzas.get(i) != null){
System.out.println(pizzas.get(i));
order = order + pizzas_count.get(pizzas.get(i)) + " x " + pizzas.get(i) + "\n";
}
}
return order;
}
My console is showing "{0=bbq}", even after adding multiple pizzas.
The getOrder method is returning (After adding 1 pizza and 1 extra):
PIZZAS
null x null
EXTRAS
1 x pasta
Any help would be much appreciated.
After first insertion of bbq pizza to pizza map, any subsequent insertion will just increment "bbq"'s counter as the following code suggest:
if(pizzas.containsValue(name)){ // if "bbq" already exist, increment its counter
// but is it really happening?
int count = pizzas_count.get(name);
pizzas_count.remove(name);
pizzas_count.put(name, count++);
// this line is not having any effect why?
}else{
pizzas.put(pizzas.size(), name);
pizzas_count.put(name, 1);
}
in your code pizzas_count.put(name, count++); is not having any effect at all. This line is actually equivalent to:
{
int count = pizzas_count.get(name);
pizzas_count.put(name, count); // count wasn't changed
count = count + 1;
}
Instead do pizzas_count.put(name, ++count);. Rest of the things are working correctly as you have written. After fixing it, the following input code:
addPizza("pizza");
addPizza("extra");
addPizza("pizza");
System.out.println(getOrder());
produces following output:
{0=pizza, 1=extra}
pizza
extra
2 x pizza
1 x extra