moody
moody

Reputation: 402

java String to an object

I want to convert a String to an object. I looked for related topics but could not find an answer. My code is:

amountShip = 5;
String name = ReadConsole.nextString(); //-->variabe of the object "Player"
gamers[i] = Player.String2Object(name, 0);

Player String2Object(String name, int amountShip) {
   Object o = name;
   Player temp = (Player)o;
   temp = new Player(name, amountShip);
   return temp;             
}

class Player {
    Player (String name, int amountShip) {
        name = name;
        ships = amountShip;
    }
    Player pl = new Player(String name, int amountShip);
}

it says

java.lang.String cannot be cast to Gameobjects.Player

My intention is to create 2 Player-objects with different instance names dynamically. If for example somebody types in "3", i want to create

Player p1 = new Player(x,y);
Player p2 = new Player(x,y);
Player p3 = new Player(x,y);

Thanks a lot in advance

Upvotes: 0

Views: 102

Answers (3)

Nikolay K
Nikolay K

Reputation: 3850

I guess all you want is to make it like this?

Player String2Object(String name, int amountShip) {
    return new Player(name, amountShip);
}

Or maybe simply

gamers[i] = new Player(name, 0);

instead of

gamers[i] = Player.String2Object(name, 0);

Another approach is to read line from console (or file) and extract name and amountShip with String.split function for example.

EDIT:

You can not dynamically create instances like in your question. But you can create array Player[] like this

// n is some int entered by user.
Player[] players = new Player[n];
for(int i = 0; i < n; ++i) {
    players[i] = new Player(x, y);
}

And then get the i-th player like this (assume that class Player have getName method)

players[i].getName();

Upvotes: 2

KMA
KMA

Reputation: 1

You don't need to convert a String to an object because a String IS an object by deafault so the casting is not needed. You can do the following:

Player String2Object(String name, int amountShip) {
    Player temp = new Player(name, amountShip);
    return temp;             
}

If you ask yourself why your code is not working the way it is that's because you are trying to cast a String into a Player. Your object o points to a String so when you try to do (Player)o you are trying to cast a string into a Player and they share no relation between them.

Upvotes: 0

user4668606
user4668606

Reputation:

String can't be converted to 'Spieler' by casting. Instead you could either use Serialization, or create a method to parse the attributes of the object from some given input.

Upvotes: 1

Related Questions