Libgdx - How to get a specific item from an array? - arrays

I have a Player class which has
int number;
In main, I store them in Array.
Array<Player> players;
How can I get a player which has for example number=2?

This question is programming in general, and has several ways to do what you say, I recommend you look for OOP.
a solution, general, would encapsulate the variable, "creating getter and setter, you need, eg:
this a simple class;
private int number;
public Player(int num){
this.number = num;
}
public int getNumber (){
return number;
}
public void setNumber (int n){
this.number = n;
}
.
In your code for search you can use the solution, using a for, or an iterator
for (int a = 0; a < players.size(); a++){
int tmpNumber = players.get(a).getNumber();
if(tmpNumber == 2){
players.get(a); //the object array with index equal to
//the value of 'a', have, number 2 stored
//in the variable 'number'
}
}
but this question I think is a little matter of taste or needs you have

I'm going to make some assumptions to demonstrate it:
Let's assume you have a constructor in your Player class:
public Player(int num){
this.number = num;
}
And you have added some players in your arraylist:
players.add(new Player(1));
players.add(new Player(2));
players.add(new Player(3));
Now loop through your array and find the one where number == 2
for (int i = 0; i < players.size(); i++){
Player tmp = players.get(i);
if(tmp.number == 2){
System.out.println("Index of player number 2: " + players.indexOf(tmp));
}
}

I realised that I'd misunderstood the question with my previous answer. Here's a better one...
Those recommending you iterate through the Array are correct, but if you have a lot of Players this will be ineffeicient. In that case, it would be better to use a Map where the key was the player number, and the value is the player itself.
Here's some sample code showing the approach (most of it is just setting up some test data)...
import java.util.HashMap;
import java.util.Map;
public class Temp {
public static void main(String[] args) {
// Create a map instead of an array
Map<Integer, Player> players = new HashMap<>();
// Quick hack just to put some data in it.
for(int i = 0; i < 1000; i++) {
players.put(i, new Player(i));
}
// Once they're in a map, retrieving them is simple...
Player playerFromMap = players.get(537);
// Check we got it right
System.out.println(playerFromMap.getNumber()); // 537
}
private static class Player {
private int number;
private Player(int number) {
this.number = number;
}
public int getNumber() {
return number;
}
}
}

Related

Passing arrays between methods, and accessing them accordingly

I'm supposed to use two methods to hold arrays, then with the two arrays determine win % of the rockets, average margin of score difference for the games lost by Houston Rockets, and the lowest Houston Rockets’ score and the corresponding game number. I primarily need help with the first one, and I can get the other tasks. I just dont know how to pass arrays from methods very well. Any help would be useful, THanks!
import java.util.Scanner;
public class MorenoJonathonRocketsStatistics
{
public static void main(String[] args)
{
System.out.println("enter rockets game scores");
int[] rockets = rocketsScore();
System.out.println("enter opponents scores");
int[] opponents = opponentsScore();
int per = percent();
System.out.println("game win percent"+per+" %");
}
public static int[] rocketsScore()
{
Scanner sc = new Scanner(System.in);
int[] rocketsScore = new int[8];
for(int i=0;i<rocketsScore.length;i++)
{
rocketsScore[i] = sc.nextInt();
}
return rocketsScore;
}
public static int[] opponentsScore()
{
Scanner sc = new Scanner(System.in);
int[] opponentsScore = new int[8];
for(int i=0;i<opponentsScore.length;i++)
{
opponentsScore[i] = sc.nextInt();
}
return opponentsScore;
}
public static int percent(int[] array, int[] array2)
{
int[] rock = rocketsScore.length();
int[] opp = opponentsScore.length();
double percent=0;
int w=0, l=0;
for(int i=0; i<rocketsScore.length;i++)
{
if(rocketsScore[i]>opponentsScore[i])
{
w++;
}
else{
l++;
}
}
percent = w/l;
return percent;
}
}
To pass array in methods, you don't need to put any brackets beside the variable that is holding the array. So, you may want to do it like below:
int per = percent(rockets, opponents);

How can I check for equality within a row, amongst all indexes?

I'm lost and don't know where to begin. I'm testing the following condition, L=W=H on Package1's method and I want to call it into the Class Runtime's main method.
I created an array of objects already. But after that, I don't know how to utilize it or even if I have to. Again I'm completely lost!...thanks for your help.
I feel as if Coding is a young man's world!, Damn you Marine Corps!
public class Package1
{
double length;
double width;
double height;
Package1(double a,double b, double c)
{
length=a;
width=b;
height=c;
}
public void isCube()
{
if(length==width && width==height)
System.out.println("The box is a cube.");
else
System.out.println("Box is not a cube. ");
}
public class Runtime{
public static void main(String[] args){
Package1[] boxes = new Package1[rows];
for(int j = 0; j < boxes.length; j++)
{
boxes[j] = new Package1(arr[j][0], arr[j][1], arr[j][2]);
}
}
}
Like this.
for(int j = 0; j < boxes.length; j++)
{
boxes[j] = new Package1(arr[j][0], arr[j][1], arr[j][2]);
boxes[j].isCube(); // this is the line that you need
}
Any element in an array can be accessed by passing the index of the item into the brackets. For instance boxes[0] is the first element in the array. boxes[ boxes.length - 1 ] is the last element in the array.

How can I put an array into a method?

I have to find the LCM of two integers using the prime factors method and function calls.
I'm up to making a function to find the prime factorization of the first number, but I'm getting errors at int x = first_number; and with System.out.print(primeFactorization).
This is my code so far:
import java.util.Scanner;
public class lcm {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int first_number;
int second_number;
System.out.print("Enter an integer: ");
first_number = reader.nextInt();
System.out.print("Enter another integer: ");
second_number = reader.nextInt();
}
public static int primeFactorization(int[] pfArray) {
int counter = 0;
pfArray = new int[10]; //created array in memory
int x = first_number;
for(int i=2;i<=x;i++){
while(x%i==0){
x=x/i;
pfArray[counter] = i;
++counter;
}
}
for(int i=0;i<counter;i++){
System.out.println(pfArray[i]);
}
}
System.out.println(primeFactorization);
}
I am just starting to learn Java, so please answer in very basic terms!
Thanks so much!
The variable first_number is declared in the first method and so cannot be used within the second method unless you pass it in as a parameter.
The only thing called primeFactorisation is the method. System.out.println requires an object (a variable) as its input. So you can't do it like that.

dynamically create objects in a loop

I am a complete newbie to Java programming, I want to dynamically create objects in Java during run time, I have checked the forms and tried some code but nothing really seems to work.
here is my code .. all help is really appreciated :)
import java.util.Scanner;
public class Main{
public static void main(String[] args){
String carName;
String carType;
String engineType;
int limit;
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of Cars you want to add - ");
limit = in.nextInt();
for(int i = 0; i <limit; i++){
Cars cars[i] = new Cars();
System.out.print("Enter the number of Car Name - ");
carName = in.nextLine();
System.out.print("Enter the number of Car Type - ");
carType = in.nextLine();
System.out.print("Enter the Engine Type - ");
engineType = in.nextLine();
cars[i].setCarName(carName);
cars[i].setCarType(carType);
cars[i].setEngineeSize(engineType);
String a = cars[i].getCarName();
String b = cars[i].getCarType();
String c = cars[i].getEngineeSize();
System.out.println(a,b,c);
}
}
}
The cars class looks like this ..
public class Cars{
public String carName;
public String carType;
public String engineeSize;
public void Cars(){
System.out.println("The Cars constructor was created ! :-) ");
}
public void setCarName(String cn){
this.carName = cn;
}
public void setCarType(String ct){
this.carType = ct;
}
public void setEngineeSize(String es){
this.engineeSize = es;
}
public String getCarName(){
return this.carName;
}
public String getCarType(){
return this.carType;
}
public String getEngineeSize(){
return this.engineeSize;
}
}
You're on the right track, there are a few errors and unnecessary bits though.
The Cars Class
Your Cars class was mostly fine, (though in my opinion Car would have made more sense) however your constructor didn't make sense, you had public void Cars(), void means "this method returns nothing", but you want to return a Cars object, meaning your constructor needs to become:
public Cars()
{
System.out.println("The Cars constructor was created ! :-) ");
}
Your Main Class
You were very close here as well, your primary issue was creating the cars array limit times:
for(int i = 0; i < limit; i++)
{
Cars cars[i] = new Cars();
//Other code
}
The array needs to be made outside the for loop.
Here is the revised Main class in full, the comments should explain fairly well what I did and why.
import java.util.Scanner;
public class Main{
public static void main(String[] args){
//The strings here were unnecessary
int limit;
Scanner in = new Scanner(System.in);
System.out.print("Enter the number of Cars you want to add - ");
limit = in.nextInt();
in.nextLine(); //nextInt leaves a newLine, this will clear it, it's a little strange, but it makes sense seeing as integers can't have newlines at the end
//Make an array of Cars, the length of this array is limit
Cars[] cars = new Cars[limit];
//Iterate over array cars
for(int i = 0; i < limit; i++)
{
//Read all the properties into strings
System.out.println("Enter the number of Car Name - ");
String carName = in.nextLine();
System.out.println("Enter the number of Car Type - ");
String carType = in.nextLine();
System.out.println("Enter the Engine Type - ");
String engineType = in.nextLine();
//Set the object at current position to be a new Cars
cars[i] = new Cars();
//Adjust the properties of the Cars at this position
cars[i].setCarName(carName);
cars[i].setCarType(carType);
cars[i].setEngineeSize(engineType);
//We still have the variables from the scanner, so we don;t need to read them from the Cars object
System.out.println(carName+carType+engineType);
}
in.close(); //We don't need the scanner anymore
}
}
Finished typing this and realized that the question is two years old :)

Multiple use a class

I am creating a game using an array, I have my Hunter class which looks somewhat like this ;
public static int x= 11;
public static int y =11;
public static String name = "H";`
And a method for its path using x and y.
I have declared hunter as an array in my board (2d array) class this way;
public Hunter hunters[] = new Hunter[5];
and the position of a hunter is declared in the board class as ;
a2[Hunter.x][Hunter.y] = Hunter.name;
Question: I want 5 hunters to appear on the board, how do I use the array to spawn additional 4 hunters? Thanks.
you created your array fine all you need to do is use it:
for (int i = 0; i < 5; ++i)
{
a2[hunters[i].x][hunters[i].y] = hunters[i].name
}
also, you need to make your Hunter members non-static
class Hunter
{
private int x, y;
public void setLocation(int x_, int y_)
{
x = x_; y = y_;
}
}
you get the idea :)
The static keyword (assuming you are using C++, java, C#) means that the variable is shared among all instances of the Hunter class. To allow each Hunter to have its own position, remove the static keyword and initialize them with a constructor.
I'll assume you're using Java bases on your use of String:
public class Hunter {
public int x;
public int y;
public String name;
public Hunter(int x, int y, string name) {
this.x = x;
this.y = y;
this.name = name;
}
}
Then to initialize 5 you would do
int numHunters = 5;
for (int i = 0; i < numHunters; i ++) {
hunters[i] = new Hunter(/* put x and y and name here */);
}
You can then use them to populate the board:
for (int i = 0; i < numHunters; i ++) {
Hunter h = hunters[i];
a2[h.x][h.y] = h.name;
}
You didn't specify what language you're using. That would help a bit.
At a minimum, try removing the "static" keyword from your property definitions.
In C#, your Hunter class might look like
public class Hunter
{
public int x;
public int y;
public String name;
public Hunter(int newX, int newY, String newName)
{
x = newX;
y = newY;
name = newName;
}
}
You create new Hunters using Hunter h1 = new Hunter(11, 11, "H");. Once created, you can do whatever with it.
You may want to do some reading up on Object Oriented Programming - see Intro to OOP esp sections 4.3 - 4.5 (they're short)

Resources