0

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

moody
  • 404
  • 7
  • 19
  • 3
    `Object o = name;Player temp = (Player)o;` What do you think this does? If you answer it then you resolved your problem. – Alexis C. May 04 '15 at 16:35
  • Java is great, but it can't do magic! Nevertheless, you should really fix formatting and give more information (see http://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors) – isnot2bad May 04 '15 at 16:38

3 Answers3

2

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();
Nikolay K
  • 3,770
  • 3
  • 25
  • 37
1

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.

0

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.

Nikolay K
  • 3,770
  • 3
  • 25
  • 37
KMA
  • 1
  • 2