Advertisement

Updating & reading from an Array

Started by June 12, 2017 11:20 AM
1 comment, last by Lactose 7 years, 5 months ago

Hi guys,

I've created three classes "Players_DB", "Print_DB" & "Server" which has the main method in it.

I'm trying to populate the array with objects created from the Players_DB class, the Players_DB class contains variables that contain player information.

Here's my server class


​package myPackage;
public class Server {


public static void main(String[] args) {


int Arr_Players_DB[] = new int [5]; //array object initialization


for (int i = 0; i < Arr_Players_DB.length ; i ++)
{
Arr_Players_DB[i] = -1; //Initialize array
}


for (int i = 0; i < Arr_Players_DB.length; i ++) // //populate array
{
Players_DB player = new Players_DB();
if (Arr_Players_DB[i] == -1)
{


Arr_Players_DB[i] = player;
}}}}

Players_DB class



package myPackage;


public class Players_DB {


public Players_DB()//Constructor
{ 


}






public int player_id;
public String player_Username;
public String player_Password;
public int x_pos;
public int y_pos;
public int room_x;
public int room_y;






}

Im getting the error "cannot convert from Players_DB to int" at this line

Arr_Players_DB = player;

From what I understand I cant store a class object inside of an array ?

I just want to reference the objects and use the array as a list so that I can go through it and then change what ever relevant code. No I won't be using this in a real world app, I'll be using sql, but I do want to know how to work with arrays. It also gives me a chance to learn java a bit more.

Your array is 5 ints. You're trying to assign a Players_DB into it, which won't work - square peg in a round hole.

You can store objects inside arrays; but the array has to be of the correct type.

Advertisement

Your array is 5 ints.

That wasn't the case earlier before some edits (see post history).

---

Currently, the problem is was Kylotan was saying.

In the earlier versions you had, the problem was that you attempted to assign the entire instance to -1, instead of accessing each member of that instance.

I.e. with the previous code you would probably want something like


Arr_Players_DB[i].player_id = -1;
//similar for the other entries.

Alternatively, the class could have a function to initialize the instance, potentially with some parameters if you need them.

Hello to all my stalkers.

This topic is closed to new replies.

Advertisement