Best algorithm to generate even strong teams - java

I got a list of players with a skill from 0-100 and a list of teams which have all their own members list.
Now I want to put the players to the teams so that teams mostly got the same size (+-1 difference is ok) and the sums of the skills should be as close at possible.
My current solution is a simple voting algorithm (teams vote players in circle, an take the next best player):
public class Teamgenerator {
public void calcTeams(){
List<Team> teams = new ArrayList<>();
teams.add(new Team("Team 1"));
teams.add(new Team("Team 2"));
List<Player> players = new ArrayList<>();
players.add(new Player("Player 1",25));
players.add(new Player("Player 2",50));
players.add(new Player("Player 3",50));
players.add(new Player("Player 4",75));
int nextTeam = 0;
while (players.size() > 0) {
int bestPlayer = findBestPlayerIndex(players);
teams.get(nextTeam).players.add(players.get(bestPlayer));
players.remove(bestPlayer);
if (nextTeam < teams.size() - 1) nextTeam++;
else nextTeam = 0;
}
for(Team t:teams){
System.out.println(t.getName()+":");
for(Player p:t.players)
System.out.println(p.getName()+", Skill "+p.getSkill());
}
}
private int findBestPlayerIndex(List<Player> players) {
//In my real programm i have to pick the skill of a more complex player object from a DB,
//depending on a specific competition, which causes i really need this index finding
int index = -1;
int highestSkill=-1;
for (int i = 0; i < players.size(); i++) {
if (players.get(i).getSkill() > highestSkill) {
highestSkill = players.get(i).getSkill();
index = i;
}
}
return index;
}
}
public class Team {
private String name;
public ArrayList<Player> players=new ArrayList<>();
public Team(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Player {
private String name;
private int skill=50; //From 0-100
public Player(String name, int skill) {
this.name = name;
this.skill = skill;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSkill() {
return skill;
}
public void setSkill(int skill) {
this.skill = skill;
}
}
The problem is that gives not the most even teams, console output is:
Team 1:
Player 4, Skill 75;
Player 3, Skill 50
Team 2:
Player 2, Skill 50;
Player 1, Skill 25
But it would be more fair if the teams are 4+1 and player 3+2.
You got any idea of a more fair algorithm? Thanks for help!

As seen on YouTube - The Fairest Sharing Sequence Ever - Standup Maths the Thue-Morse Sequence is probably your best bet for minimising first turn advantage.
Wikipedia:
In mathematics, the Thue–Morse sequence, or Prouhet–Thue–Morse sequence, is the binary sequence (an infinite sequence of 0s and 1s) obtained by starting with 0 and successively appending the Boolean complement of the sequence obtained thus far. The first few steps of this procedure yield the strings 0 then 01, 0110, 01101001, 0110100110010110, and so on, which are prefixes of the Thue–Morse sequence. ...
Intro Computer Science - Princeton
//Copyright © 2000–2016, Robert Sedgewick and Kevin Wayne.
public class ThueMorse {
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
String thue = "0";
String morse = "1";
for (int i = 1; i <= n; i++) {
String t = thue; // save away values
String m = morse;
thue += m;
morse += t;
}
System.out.println(thue);
}
}
Porting from a Python answer, to get a SO copyright approved version:
public static int whoseTurn(int turnCount){
return Integer.bitCount(turnCount) % 2;
}
Using this turn order, with a sorted list based on skill level should give fairer teams, and meet your constraint of being within +-1 member.
Verified against the online encyclopedia of integer sequences (A010060) by generating the first 105 digits.
import java.util.stream.IntStream;
public class NodeStack {
public static int whoseTurn(int turnCount){
return Integer.bitCount(turnCount) % 2;
}
public static void main(String[] args) {
System.out.print("OEIS: ");
IntStream.range(0,105).map(NodeStack::whoseTurn).forEach(i->System.out.print(i+", "));
String result = IntStream.range(0,105).map(NodeStack::whoseTurn).collect(StringBuilder::new,(sb,i)->sb.append(i), StringBuilder::append).toString();
System.out.println();
IntStream.range(1,105).forEach(
(i)-> System.out.println(i+"# "+result.substring(0,i)+ " : " +diff(result.substring(0,i)))
);
}
public static int diff(String s){
int zero = 0;
int one = 0;
for (char c:s.toCharArray()){
if (c=='0')zero++;
if (c=='1')one++;
}
return zero-one;
}
}

Related

How to make a selection sort without using the compare() method in java?

Greetings StackOverFlow Community!
I have recently started studying java at school, and one of the assignments is to create a sorting method, like selection sort or insertion sort, without using java's own built-in functions. I have looked online a lot, and all of the methods I have found are for Arrays and not ArrayLists. The goal with the assignment is to sort a dog class after tail length, and if the dogs have the same tail length, to also sort after name.
So far this is what I have done;
Dog Class
public class Dog {
private static final double DEFAULT_TAIL_SIZE = 10.0;
private static final double DEFAULT_TAX_SIZE = 3.7;
private static int count;
private String name;
private String breed;
private int age;
private int weight;
private double tailLenght;
public Dog(String name, String breed, int age, int weight) {
//count++;
this.name = name;
this.age = age;
this.breed = breed;
this.weight = weight;
this.tailLenght = tailLenght;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getBreed() {
return breed;
}
public int getWeight() {
return weight;
}
public void setAge(int age) {
age = age <= 0 ? 1 : age;
}
public double getTailLength() {
if (breed.equals("Tax") || breed.equals("dachshund")||breed.equals("tax") || breed.equals("Dachshund")) {
return tailLenght = DEFAULT_TAX_SIZE;
} else {
return tailLenght = age * weight/DEFAULT_TAIL_SIZE;
}
}
#Override
public String toString() {
//System.out.println(String.format("name=%s breed=%s age=%d weight=%d taillenght=%.1f", name, breed, age, weight, getTailLength()));
return name + " " + breed + " " + age + " " + weight + " " + getTailLength();
}
And this is the sorting code I have made, that was not accepted due to the code using in-built java sorting methods. This is the only code I'm allowed to edit during this assignment
public class DogSorter {
public void sort(ArrayList<Dog> dogs) {
dogs.sort(new Comparator<Dog>() {
#Override
public int compare(Dog d1, Dog d2) {
int comparison = 0;
comparison = Double.valueOf(d1.getTailLength()).compareTo(d2.getTailLength());
if (comparison == 0) {
comparison = String.valueOf(d1.getName()).compareTo(d2.getName());
}
return comparison;
}
});
}
And lastly this is the runner code we received from our teachers
import java.util.ArrayList;
import java.util.Random;
public class DogSorterRunner {
private static final int NUMBER_OF_DOGS = 12;
private static final Random RND = new Random();
private static final String[] NAMES = { "Fido", "Karo", "Molly", "Bella", "Wilma", "Doris", "Sigge", "Charlie",
"Ludde", "Bamse", "Lassie", "Ronja", "Ratata", "Maki", "Dora", "Luna", "Spike", "Mumsan", "Cherie" };
private static final String[] BREEDS = { "Labrador", "Golden retriever", "Tax", "Dachshund" };
private static String getRandomValueFromArray(String[] array) {
return array[RND.nextInt(array.length)];
}
private static String randomName() {
return getRandomValueFromArray(NAMES);
}
private static String randomBreed() {
return getRandomValueFromArray(BREEDS);
}
private static int randomNumber() {
return RND.nextInt(10) + 1;
}
public static void main(String[] args) {
ArrayList<Dog> dogs = new ArrayList<>();
for (int n = 0; n < NUMBER_OF_DOGS; n++) {
Dog dog = new Dog(randomName(), randomBreed(), randomNumber(), randomNumber());
dogs.add(dog);
}
new DogSorter().sort(dogs);
for (Dog dog : dogs) {
System.out.println(dog);
}
}
Any help and feedback would be greatly appreciated!
The point of the assignment is that you should implement selection or insertion sort by yourself instead of using Java's built-in sort function. That is how you show some knowledge in implementing sorting algorithms.
Here is an example of a selection sort, which is based on your conditions (tail & name) and should give you a feeling of how the functions should look like. To do some more exercise, I suggest that you try to implement insertion sort by yourself.
public class DogSorter {
public void sort(ArrayList<Dog> dogs) {
dogs.sort(new Comparator<Dog>() {
#Override
public int compare(Dog d1, Dog d2) {
int comparison = 0;
comparison = Double
.valueOf(d1.getTailLength())
.compareTo(d2.getTailLength());
if (comparison == 0) {
comparison = String
.valueOf(d1.getName())
.compareTo(d2.getName());
}
return comparison;
}
});
}
public void selectionSort(ArrayList<Dog> dogs) {
int n = dogs.size();
// One by one move boundary of unsorted subarray
for (int i = 0; i < n - 1; i++) {
// Find the minimum element in unsorted array
int min_idx = i;
for (int j = i + 1; j < n; j++) {
Dog d1 = dogs.get(j);
Dog d2 = dogs.get(min_idx);
int comparison = Double
.valueOf(d1.getTailLength())
.compareTo(d2.getTailLength());
if (comparison == 0) {
comparison = String
.valueOf(d1.getName())
.compareTo(d2.getName());
}
if (comparison < 0)
min_idx = j;
}
// Swap the found minimum element with the first
// element
// using built in swap
// Collections.swap(dogs, min_idx, i);
// using classic temp method
Dog temp = dogs.get(min_idx);
dogs.set(min_idx, dogs.get(i));
dogs.set(i, temp);
// using classic method without temp element
// dogs.set(i, dogs.set(min_idx, dogs.get(i)));
}
}
}
Here is also a repl, where you can see this function in practice: https://repl.it/repls/VividMeekPlans

Getting Java methods from one object and a constructor from another object

I have three class Homework that has my main(...), GradeArray, which has my methods, and StudentGrade, which has my constructor.
Currently , which is clearly wrong, I have in Homework:
GradeArray grades = new GradeArray();`
In GradeArray at the top I have StudentGrade[] ArrayGrades = new StudentGrade[size]; however this method did not give me both the contructor and the methods. I know I don't need three classes for this but my professor wants three class. How do I declare an array that has attributes from two classes so that I can get the methods from GradeArray and the constructor from StudentGrade?
Thank you for you time and help.
Here is all of my code
package homework1;
public class Homework1
{
public static int pubSize;
public static String pubCourseID;
public static void makeVarsPub(int maxSize, String courseID) //this is to makes the varibles public
{
pubSize = maxSize;
pubCourseID = courseID;
}
public int giveSize()
{
return pubSize;
}
public static void main(String[] args)
{
int maxSize = 100;
String courseID = "CS116";
//this is to makes the varibles public
makeVarsPub(maxSize, courseID);
StudentGrade grades = new StudentGrade();
grades.insert("Evans", 78, courseID);
grades.insert("Smith", 77, courseID);
grades.insert("Yee", 83, courseID);
grades.insert("Adams", 63, courseID);
grades.insert("Hashimoto", 91, courseID);
grades.insert("Stimson", 89, courseID);
grades.insert("Velasquez", 72, courseID);
grades.insert("Lamarque", 74, courseID);
grades.insert("Vang", 52, courseID);
grades.insert("Creswell", 88, courseID);
// print grade summary: course ID, average, how many A, B, C, D and Fs
System.out.println(grades);
String searchKey = "Stimson"; // search for item
String found = grades.find(searchKey);
if (found != null) {
System.out.print("Found ");
System.out.print(found);
}
else
System.out.println("Can't find " + searchKey);
// Find average and standard deviation
System.out.println("Grade Average: " + grades.avg());
System.out.println("Standard dev; " + grades.std());
// Show student grades sorted by name and sorted by grade
grades.reportGrades(); // sorted by name
grades.reportGradesSorted(); // sorted by grade
System.out.println("Deleting Smith, Yee, and Creswell");
grades.delete("Smith"); // delete 3 items
grades.delete("Yee");
grades.delete("Creswell");
System.out.println(grades); // display the course summary again
}//end of Main
}//end of homework1
package homework1;
class GradeArray
{
int nElems = 0; //keeping track of the number of entires in the array.
Homework1 homework1InfoCall = new Homework1(); //this is so I can get the information I need.
int size = homework1InfoCall.giveSize();
StudentGrade[] ArrayGrades = new StudentGrade[size];
public String ToString(String name, int score, String courseID)
{
String res = "Name: " + name + "\n";
res += "Score: " + score + "\n";
res += "CourseID " + courseID + "\n";
return res;
}
public String getName(int num) //returns name based on array location.
{
return ArrayGrades[num].name;
}
public double getScore(int num) //returns score based on array location.
{
return ArrayGrades[num].score;
}
public void insert(String name, double score, String courseID) //part of the insert method is going to be
//taken from lab one and modified to fit the need.
{
if(nElems == size){
System.out.println("Array is full");
System.out.println("Please delete an Item before trying to add more");
System.out.println("");
}
else{
ArrayGrades[nElems].name = name;
ArrayGrades[nElems].score = score;
ArrayGrades[nElems].courseID = courseID;
nElems++; // increment the number of elements
};
}
public void delete(String name) //code partly taken from lab1
{
int j;
for(j=0; j<nElems; j++) // look for it
if( name == ArrayGrades[j].name)
break;
if(j>nElems) // can't find it
{
System.out.println("Item not found");
}
else // found it
{
for(int k=j; k<nElems; k++) // move higher ones down
{
boolean go = true;
if ((k+2)>size)
go = false;
if(go)
ArrayGrades[k] = ArrayGrades[k+1];
}
nElems--; // decrement size
System.out.println("success");
}
}
public String find (String name){ //code partly taken from lab1
int j;
for(j=0; j<nElems; j++) // for each element,
if(ArrayGrades[j].name == name) // found item?
break; // exit loop before end
if(j == nElems) // gone to end?
return null; // yes, can't find it
else
return ArrayGrades[j].toString();
}
public double avg() //this is to get the average
{
double total = 0;
for(int j=0; j<nElems; j++)
total += ArrayGrades[j].score;
total /= nElems;
return total;
}
public double std() //this is to get the standard deviation. Information on Standard deviation derived from
//https://stackoverflow.com/questions/18390548/how-to-calculate-standard-deviation-using-java
{
double mean = 0; //this is to hold the mean
double newSum = 0;
for(int j=0; j < ArrayGrades.length; j++) //this is to get the mean.
mean =+ ArrayGrades[j].score;
for(int i=0; i < ArrayGrades.length; i++) //this is to get the new sum.
newSum =+ (ArrayGrades[i].score - mean);
mean = newSum/ArrayGrades.length; //this is to get the final answer for the mean.
return mean;
}
public StudentGrade[] reportGrades() //this is grade sorted by name
{
int in,out;
char compair; //this is for compairsons.
StudentGrade temp; //this is to hold the orginal variable.
//for the first letter cycle
for(out=1; out<ArrayGrades.length; out++)
{
temp = ArrayGrades[out];
compair= ArrayGrades[out].name.charAt(0);
in=out;
while(in>0 && ArrayGrades[in-1].name.charAt(0) > compair)
{
ArrayGrades[in] = ArrayGrades[in-1];
in--;
}
ArrayGrades[in]=temp;
}
//this is for the second run.
for(out=1; out<ArrayGrades.length; out++)
{
temp = ArrayGrades[out];
compair= ArrayGrades[out].name.charAt(1);
in=out;
while(in>0 && ArrayGrades[in-1].name.charAt(1) > compair)
{
ArrayGrades[in] = ArrayGrades[in-1];
in--;
}
ArrayGrades[in]=temp;
}
return ArrayGrades;
}
public StudentGrade[] reportGradesSorted() //this is grades sorted by grades.
//this is grabbed from lab2 and repurposed.
{
int in,out;
double temp;
for(out=1; out<ArrayGrades.length; out++)
{
temp=ArrayGrades[out].score;
in=out;
while(in>0 && ArrayGrades[in-1].score>=temp)
{
ArrayGrades[in]= ArrayGrades[in-1];
in--;
}
ArrayGrades[in].score=temp;
}
return ArrayGrades;
} //end of GradeArray
package homework1;
public class StudentGrade extends GradeArray
{
public String name;
double score;
public String courseID;
public void StudentGrade (String name, double score, String courseID) //this is the constructor
{
this.name = name;
this.score = score;
this.courseID = courseID;
}
}//end of StudentGrade class.
First, I feel #Alexandr has the best answer. Talk with your professor.
Your question doesn't make it quite clear what you need. However, it sounds like basic understanding of inheritance and class construction would get you going on the right path. Each of the 3 classes will have a constructor that is unique to that type. Each of the 3 classes will have methods and data (members) unique to those types.
Below is just a quick example of what I threw together. I have strong concerns that my answer is actually what your professor is looking for however--it is not an object model I would suggest--just an example.
public class Homework {
private String student;
public Homework(String name) {
student = name;
}
public String getStudent() {
return student;
}
}
public class StudentGrade extends Homework {
private String grade;
public StudentGrade(String grade, String name) {
super(name);
this.grade = grade;
}
public String getGrade() {
return grade;
}
}
public class HomeworkGrades {
public List<StudentGrade> getGrades() {
// this method isnt implemented but should
// be finished to return array of grades
}
}
Take a look and see if that helps you understand something about inheritance and class construction.
Hopefully you can infer a bit about inheritence (StudentGrade inherits -- in java extends -- from HomeWork) and class construction.
Thnx
Matt
I change the array creation in Homework1 to be StudentGrade grades = new StudentGrade(); and I added extends GradeArray to the StudentGrade class. it is now public class StudentGrade extends GradeArray.

How to read through file and compute win/loss chart from records given in file?

My assignment is I have to manage a soccer league.There is a soccer league (text file) that I have to import into the program.Each line of the imported file displays the outcome of a single game:the name of two teams together with the scores like
Peter 4 Tiger 3
Sky 2 Peter 0
Tiger 1 Sky 2
I have to write the program to read this text file and displays the output of team records like
Team Wins Losses
Peter 1 1
Tiger 0 2
Sky 2 0
I don't understand how to read through the lines and calculate the wins and losses associated with each team/String.
import java.util.*;
import java.io.*;
public class SoccerLeagueStandings
{
public static void main(String[] args) throws IOException
{
File inFile = new File("LeagueScore.txt");
if(! inFile.exists())
{
System.out.println("Error could not open the file");
return;
}
String Panthers="Panthers";
String Tigers = "Tigers";
String Sky = "Sky";
Scanner input = new Scanner (inFile);
int PW=0;
int PL=0;
int TW =0;
int TL = 0;
int SW=0;
int SL=0;
while (input.hasNextLine())
{
String firstTeam=input.next();
input.nextInt();
int firstScore=input.nextInt();
String secondTeam=input.next();
input.nextInt();
int secondScore = input.nextInt();
if (firstScore>secondScore)
{
if (firstTeam.equals(Panthers))
{
PW+=1;
}
if (firstTeam.equals(Tigers))
{
TW+=1;
}
if (firstTeam.equals(Sky))
{
SW+=1;
}
}
}
}
}
The main challenge in this problem is to keep track of the wins and losses of each team.
So i suggest to create a class called Team which holds: name, winsCount, lossCount. This class represents a single team along with its wins and loss count.
Create an arrayList of Team and fill it using the file content.
So your algorithm would be as the following:
Parse the file line by line using Scanner.
Split each line by space in order to get the teams and their scores.
Compare the scores of the teams.
Add the winner team to the ArrayList OR increment its winsCount if already exist.
Do the same for the loser team.
Below is a non-tested sample code:
Following is the Team class:
public class Team {
private String name;
private int winsCount;
private int lossCount;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getWinsCount() {
return winsCount;
}
public void setWinsCount(int winsCount) {
this.winsCount = winsCount;
}
public int getLossCount() {
return lossCount;
}
public void setLossCount(int lossCount) {
this.lossCount = lossCount;
}
}
Below is how to fill the arraylist from the input file:
private void generateWinsLossesFromInput(String filePath)
{
Scanner input = new Scanner(filePath);
List<Team> teams = new ArrayList<Team>();
while(input.hasNext())
{
String match = input.next();
// Split the line and get teams and their scores.
String[] splittedMatch = match.split("\\s+");
String firstTeam = splittedMatch[0];
int firstTeamScore = Integer.parseInt(splittedMatch[1]);
String secondTeam = splittedMatch[2];
int secondTeamScore = Integer.parseInt(splittedMatch[3]);
if(firstTeamScore > secondTeamScore)
{
addWinner(firstTeam, teams);
addLoser(secondTeam, teams);
}
else
{
if(secondTeamScore > firstTeamScore)
{
addWinner(secondTeam,teams);
addLoser(firstTeam, teams);
}
}
}
}
private void addWinner(String team, List<Team> teams)
{
int index = 0;
for(index = 0; index<teams.size(); index++)
{
Team t = teams.get(index);
if(t.getName().equalsIgnoreCase(team))
{
// Team already exists, so just increment its winsCount
t.setWinsCount(t.getWinsCount() + 1);
break;
}
}
if(index == teams.size())
{
// team not found, So add it as new team to the list.
Team t = new Team();
t.setName(team);
t.setWinsCount(1);
t.setLossCount(0);
teams.add(t);
}
}
private void addLoser(String team, List<Team> teams)
{
int index = 0;
for(index = 0; index<teams.size(); index++)
{
Team t = teams.get(index);
if(t.getName().equalsIgnoreCase(team))
{
// Team already exists, so just increment its loss count.
t.setLossCount(t.getLossCount() + 1);
break;
}
}
if(index == teams.size())
{
// team not found , then add new team to the list
Team t = new Team();
t.setName(team);
t.setWinsCount(0);
t.setLossCount(1);
teams.add(t);
}
}
At the end, you would be able to iterate over the array list and print out each team along with its Wins and loss counts.

Sorting an array of integers in descending order and relating it to its corresponding string array

I am trying to output the names and corresponding scores in descending order. Having an array of strings and another array of integers, I am trying to relate the two arrays. I used Arrays.sort and tries to get the indices. The indices is then to be used to arrange the names in similar location as the corresponding scores. I have this code but I get run time error saying unfortunately, your app has stopped. Can anyone please help me on what to be done to achieve my goal here? Thank you so much!
int score[]= new int[4];
score[0]= 10;
score[1]= 50;
score[2]= 20;
score[3]= 60;
String names[] = new String[4];
names[0]= "player1";
names[1]= "player2";
names[2]= "player3";
names[3]= "player4";
Arrays.sort(score);
int index_array[] = new int[4];
int m = 0;
for(m = 0; m <4; m++){
index_array[m]=Arrays.binarySearch(score ,score[m]);
l = index_array[0];
}
for(int i = 0; i<4; i++){
if(l == score[i]){
j = i;
}
}
String name = names[m];
show.setText(name + " " + Integer.toString(l));
Create Player model which holds player's name and score and then use Comparator to sort players by score.
Player model:
class Player {
private String name;
private int score;
public Player(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
public String toString() {
return "name=" + name + "; score=" + score;
}
}
Comparator:
class PlayerComparator implements Comparator<Player> {
public int compare(Player p1, Player p2) {
return p1.getScore() < p2.getScore() ? -1
: p1.getScore() > p2.getScore() ? 1 : 0;
}
}
And an example of usage:
public class PlayerTest {
public static void main(String[] args) {
int score[]= new int[4];
score[0]= 10;
score[1]= 50;
score[2]= 20;
score[3]= 60;
String names[] = new String[4];
names[0]= "player1";
names[1]= "player2";
names[2]= "player3";
names[3]= "player4";
Player[] players = new Player[names.length];
for(int i = 0; i < names.length; i++) {
players[i] = new Player(names[i], score[i]);
}
Arrays.sort(players, new PlayerComparator());
}
}
you need to associate the score and the user name. Currently, you are associating them by array index. when you sort the scores, the indices of the scores will change.
Try something like this:
class Score implements Comparable<Score>
{
int score;
String player;
public Score(int theScore, String thePlayer)
{
score = theScore;
player = thePlayer;
}
public int compareTo(Score)
{
... compare based on the int score value ...
}
... getters. setters optional ...
}
List<Score> scoreList = new ArrayList<Score>();
... fill scoreList with Score objects. ...
Collections.sort(scoreList);
This is a design smell. You shouldn't have two parallel arrays. Instead, you should have a single array of Player objects, where each Player would have a name and a score.
Storing the arra of players by name or by score would then be extremely simple.
Java is an OO language. Use objects.
public class Player
private final String name;
private int score;
public Player(String name, int score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
...
Player[] players = new Player[4];
players[0] = new Player("player1", 10);
...

storing command line args in an array class

Musical Chairs. Musical Chairs is a children’s game where the players walk around a group of chairs while some music is playing. When the music stops, everyone must sit down. But, there is one less chair than there are people, so someone gets left out. And, indeed, that person is out of the game. A chair is removed. And the game is played again; someone else goes out. This continues until there is only one player left, the winner.
I am having problems storing the command line arguments in the player[]
here is my code
import java.util.*;
public class MusicalChairs {
Player [] players;
Random r = new Random();
public static void main(String[] args){
MusicalChairs mc = new MusicalChairs();
mc.setUpGame(args);
}
public void setUpGame(String [] p){
System.out.println("This is how we stand.......");
for (int i = 0; i < p.length; i++){
System.out.println(p[i]+" is "+ Player.Status.IN);
}
}
public void showStatus(){
}
public void winner(){
System.out.println("is the winner");
}
}
class Player{
enum Status{IN,OUT};
private String name;
private Status status;
public Player(String n){
name=n;
}
public String getName(){
return name;
}
public void setStatus(Status s){
status=s;
}
public Status getStatus(){
return status;
}
public String toString(){
String ret = name;
if(status==Status.IN){
ret="IN ";
}
else{
ret="OUT ";
}
return ret;
}
}
You're not storing the arguments in your array. If your question is how to do it, then you should:
Initialize the players array.
For each argument, you must create a Player object and store it in the array.
Use the data in your program.
This could be done like this:
public void setUpGame(String [] p) {
System.out.println("This is how we stand.......");
//Initialize the `players` array.
players = new Player[p.length];
for (int i = 0; i < p.length; i++){
System.out.println(p[i]+" is "+ Player.Status.IN);
//For each argument, you must create a `Player` object and store it in the array.
players[i] = new Player(p[i]);
players[i].setStatus(Status.IN);
}
//Once your array is filled, use the data in your program.
//...
}
The question is still open: What's your specific problem?
I think you need to update your code to create new players and maintain the reference in your array...
public void setUpGame(String [] p){
System.out.println("This is how we stand.......");
// You may want to check for a 0 number of players...
players = new Player[p.length];
for (int i = 0; i < p.length; i++){
players[i] = new Player(p[i]);
players[i].setStatus(Player.Status.IN);
System.out.println(players[i].getName()+" is "+ players[i].getStatus());
}
}

Categories