The following program asks to give the number of the players and their names. I want to put the names in a arraylist and return them by their id.
private static ArrayList<Player>Playerlist=new ArrayList<Player>();
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s;
{
System.out.printf("number of players(2 -4)? ");
int p = scanner.nextInt();
scanner.nextLine();
for(int i=0;p>4 || p<2;i++)
{
System.out.printf("only 2-4 players.\n");
System.out.printf("number of players(2 -4)?");
p = scanner.nextInt();
scanner.nextLine();
}
Player pl=new Player();
int m=1;
for(int k=1;k<=p;k++)
{
System.out.printf("give the name of the player %d: ",k);
s= scanner.nextLine();
pl.setName(s,m);
System.out.printf(pl.getName());
Playerlist.add(pl);
m++;
}
public class Player {
private String name;
private int id;
public Player () {
}
Player(String val,int k) {
this.name = val;
this.id=k;}
/**
* getName
*
*/
public String getName () {
return name;
}
/**
* setName
*/
public void setName (String val,int k) {
this.name = val;
this.id=k;
}
public void displayStudentDetails(){
System.out.println("ID is "+id);
System.out.println("Name is "+name)};
i dont know how to do the search by id...i have tried many things but they didnt work....
A better solution would be to use a HashMap<Integer, String>, with the id being the key and the name being the value. Then you can search easily:
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "Robert");
map.put(2, "Jeff");
Then to search:
String name = map.get(1); // will return "Robert"
Edit: Ok, if you need more data than just name, like score, you will need to create a data type. Like:
public class Player {
private String name;
private int score;
// etc.
public Player(String name, int score) {
this.name = name;
this.score = score;
}
}
And then you can add objects of this type to the map like:
map.put(1, new Player("Robert", 10));
Ignoring the fact that you should have classes in different files without global variables at this time...
/**
* Searches the PlayerList Arraylist for a Player having the ID of the parameter passed
*/
public Player searchByID(int id) {
//Do some sort of check on id to ensure its valid?
for (int i = 0; i < PlayerList.size(); i++) {
if (PlayerList.get(i).getID() == id) {
return PlayerList.get(i);
}
}
return null;
}
ArrayList is probably the wrong data structure. If you want to retrieve the elements in id order, you want a HashMap if the ids are all regular in the sense that you can be sure of things like "ids are 1 to 10 and there are no unused ids". If the id set is sparse, you'll want a to use TreeMap or TreeSet depending on your other use cases.
If the situation where you need to get the player by ID is based exactly on how your code is adding players, then you can just do:
public Player getPlayerById(int id)
{
return PlayerList.get(id - 1);
}
Since you are assigning player ids linearly starting at 1 for the first player. If you are modifying or otherwise changing the order of players and ids then you will need to use one of the other suggestions (but if you are not doing that then this is the most optimized solution).
Note: The code above will throw an ArrayIndexOutOfBoundsException if the id does not exist in the player list, do you may want to modify the code depending on how you want to handle that.
Related
Hello in my monopoly game i need to make sure no inputted player names are the same to avoid confusion using an arraylist in java any way how to do it so only one player can have one name
public class Player {
private ArrayList<Property> properties = new ArrayList<Property>();
private final String name;
private int position;
private int money = 0;
public boolean inJail = false;
public int outOfJailCards = 0;
public int turnsInJail = 0;
public Player(String name){
this.name = name;
position = 0;
}
public String getName() {
return name;
}
// in monopoly.java
static ArrayList<Player> createPlayers(int numPlayers){
ArrayList<Player> players = new ArrayList<>();
for(int i = 1; i <= numPlayers; i++){
System.out.print("Player " + i + " name: ");
players.add(new Player(Input.read()));
}
return players;
}
}
import java.util.List;
import java.util.Scanner;
public class Input {
public static String read(){
Scanner scanner = new Scanner(System.in);
return scanner.nextLine();
}
Instead of directly adding the player to the array list, check with .contains() first. If not, ask for re-input. You will not be able to do this directly with a for loop, you will need to restructure your code.
PS: This sounds very much like homework in a programming course.
you can save the input from the user into a variable and check if the name already exists in the list:
String input = Input.read();
if(!list.stream().findAny(s -> s.getName().equals(input)).isPresent()({
players.add(new Player(input));
}
Stream API were used to check if name already exists in the list, but you could also use the .contains method, but first you need to override the equals method in your Player class.
I'm fairly new to Java and I've been trying to add an object to an ArrayList storing the respective object type. However, there is a catch. I want to have an indefinite amount of objects added into the ArrayList. The length is based on the user input, so I can't define them beforehand and use .add() after initializing the fields.
This is the class in question. There are 4 private fields and public getters and setters (only two included for context):
public class Player {
private int id; // This will be unique for each player.
private int roundScore; // Score accumulated during a round, suspect to be reset if the player rolls a double.
private int bankScore; // Secured score of a player.
private String name;
public Player() {
roundScore = 0;
bankScore = 0;
}
public void setID(int id) {
this.id = id;
}
public int getID() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
And this is the method I tried to use to generate players (this method is in another class):
public void generatePlayers(int num) {
Player dummyPlayer = new Player();
List<Player> playerList = new ArrayList<Player>();
Scanner sr = new Scanner(System.in);
for (int i = 0; i < num; i++) {
dummyPlayer.setID(i);
System.out.println("\nWhat is the name of player " + i++ + "?");
dummyPlayer.setName(sr.nextLine());
System.out.println(dummyPlayer.getName() + ", welcome to the game!");
playerList.add(dummyPlayer); // Oops, this is dumb.
}
}
The idea was to create an instance of a player object called "dummyPlayer", store the variables into the object and add the object into the ArrayList. "Should be fine, right?" or so I thought before I realized I basically added multiple instances of the same object which will all change if I change one of them because referencing is a thing.
Is there a way to individually set the fields of each value in the array? I'm sorry if I missed something vital or asking something stupid. I tried to search other questions but they didn't quite click. Thank you for your time.
As commented by #tgdavies, change generatePlayers() to move the new Player() line inside the for loop like so:
public void generatePlayers(int num) {
List<Player> playerList = new ArrayList<Player>();
Scanner sr = new Scanner(System.in);
for (int i = 0; i < num; i++) {
Player dummyPlayer = new Player();
dummyPlayer.setID(i);
System.out.println("\nWhat is the name of player " + i++ + "?");
dummyPlayer.setName(sr.nextLine());
System.out.println(dummyPlayer.getName() + ", welcome to the game!");
playerList.add(dummyPlayer); // Oops, this is dumb.
}
}
This way for every iteration of the for loop you create a new instance of Player, and you get to keep the as-is dummyPlayer variable (since local variables only exist within the block it is stated).
If for some reason there is a need to reference the dummyPlayer variable outside the for loop, you can state just the type and variable name before the loop and instantiate the Player class in the loop:
//... Same as above
Player dummyPlayer; //beware of null
for (int i = 0; i < num; i++) {
dummyPlayer = new Player(); //Player class instantiation
//... Same as above
}
dummyPlayer.toString(); //you can still reference dummyPlayer from here
I'm trying to cycle through objects and update a variable each time, I have a Player class that has all of the following variables:
Name, s1 ,s2, s3,...., s11, total
I want to go through each variable from the start to the end and adding the score at each go for each player (all the players are in an array list).
I'm not sure what the best way to do this is, is there a way to select a specific object and then add the variable depending on who go it is.
if you need any more information please ask and thanks in advance for any help given.
public void addScore(int turn, int score){
Player.setScore( turn, score);
}
You can cycle in array list with a simple for, like this:
ArrayList<Player> players = ...;
for (int i = 0; i < players.size(); i++) {
/*Operations on players[i] = the current player*/
}
To take and modify the variables of your player you can create getter and setter methods for each parameter like this:
private String name;
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
If you have a lot of variables (s1, s11) of the same type, use an array:
int[] scores = new int[11];
So you can use another for cycle.
If I understand this question correctly, each player has a name, 11 scores, and a total. You seem to be asking how to iterate through a list of players and make the total equal to the sum of the 11 scores.
A more usual (in an OO language) approach would be just to ensure that the total is always equal to the sum of the 11 scores. (This is called "encapsulation", and is the fundamental idea behind all of object-oriented programming.) This is very easy to accomplish (for ease of programming, I put the scores in an array):
public class Player {
private String name ;
private int[] scores ;
private int total ;
public Player(String name) {
this.name = name ;
this.scores = new int[11] ; // all initialized to zero, as is total.
}
public void setScore(int whichScore, int score) {
int change = score - scores[whichScore] ;
scores[whichScore] = score ;
total = total + change ;
}
public int getScore(int whichScore) {
return scores[whichScore] ;
}
public int getTotal() {
return total ;
}
public String getName() {
return name ;
}
public void setName(String name) {
this.name = name ;
}
}
Now your question is redundant: the total is always equal to the sum of the scores, so there is no need to iterate through the players to compute the total anywhere in your code. You can get the total for each player with
for (Player p : listOfPlayers) {
System.out.println("Player "+p.getName()+" has total score "+p.getTotal());
}
I have one class which is called people where I keep track of 50 people, their rank, name, age and order. Then I have a second class called rearrange where I have to change the position of the int order. So it will change up the order, like order 1 which is in position 0, will be moved to position 48th. I need to do the whole thing without using any loop.
class people {
int order[] = new int[50];
for(int j=0; j<order.length; j++) {
order[j] = "order" + j;
System.out.print(order);
}
}
class rearrange {
// In here i need to change the position of the int order, and need to do this without using any loop.
}
Shouldn't rearrange be a method of the people class? Classes are usually created for Nouns, Verbs are usually functions or methods of a class. And wouldn't it be better to have a class "Person" and make an array of 50 of them, and simply change their index to change their order?
Consider something like this:
public class Person //create Person class with the attributes you listed
{
private int rank;
private int age;
private String name;
public Person(int rank, int age, String name) //constructor
{
this.rank = rank;
this.age = age;
this.name = name;
}
}
public class MainClass
{
Person[] people = new Person[50]; //array of Persons, containing 50 elements
public static void main(String[] args)
{
for(int i = 0; i < people.length(); i++)
{
people[i] = new Person(something, something, something); //give all the people some values, you'll have to decide what values you are giving them
}
//do something with the rearrange function here
}
public static void rearrange(int target, int destination) //this is just a "swap" function
{
Person temp = people[destination];
people[destination] = people[target];
people[target] = temp;
}
}
Hey there guys and gals.
Background:
I'm working on a high score program for homework that asks for 5 names and 5 scores. After the names with the corresponding scores are entered the program sorts the two ArrayLists by highest score. Finally it displays the names with their scores in sorted order.
Question:
I'm having the devil of a time trying to sort the ArrayLists , do you any advice on sorting ArrayLists ?
Code:
import java.util.*;
public class Assignment6
{
public static void main(String args[])
{
ArrayList<String> names = new ArrayList();
ArrayList<Integer> scores = new ArrayList();
initializeArrays(names, scores);
//sortArrays(names, scores);
displayArrays(names, scores);
}
public static void initializeArrays(ArrayList names, ArrayList scores)
{
Scanner in = new Scanner(System.in);
for(int i=0; i<5; i++)
{
System.out.println("Enter the name for score # " + (i+1) + ": ");
names.add(in.next());
System.out.println("Enter the score for score # " + (i+1) + ": ");
scores.add(in.next());
}
}
public static void sortArrays(ArrayList names, ArrayList scores)
{
for(int i=0; i<5; i++)
{
if(scores[i] < scores[i+1])
{
Collections.swap(scores,a, b);
Collections.swap(names,a, b);
}
}
}
public static void displayArrays(ArrayList names, ArrayList scores)
{
System.out.println("Top Scorers: ");
System.out.println(names);
System.out.println(scores);
}
}
Create one object with fields: name and score with implements Comparable.
Then having ONLY one ArrayList use Collections.sort(list);
You can wrap both score and name into one object and store it in a list.
class Result implements Comparable<Result>{
private String name;
private int score;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
#Override
public int compareTo(Result other) {
return this.score - other.score;
}
}
Now you can use Collections.sort(List<Result>) to sort them out based on the highest score.
ok, do you want to print something like that A-{Bob, Alex, ...}, where Bob is a name and A is scope, you can do it using one object as described by Alex, but if its home work I think your teacher want to see some comuter science data structure, in that case is Associative_array will be better. You can implement it by your side or use java implementation. Java provide us Map [T, V] , and implementation, for your case is TreeMap, where T - is scope and V - is a List of the Name because a lot of people can have the same scope.
So, result structure will be like that
Map<String, List<String>> sortedScopes = new TreeMap<>();
and using :
List<String> names = sortedScopes.get(scope);
if(names == null){
names = new ArrayList<>();
sortedScopes.put(scope, names);
}
names.add(name)
In that solution you will have just a 2 methods initialize and display,
Sorting by scope will execute on demand