2015-05-04 178 views
0

我想將String轉換爲對象。我查找了相關主題,但找不到答案。我的代碼是:java String to a object

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); 
} 

它說

java.lang.String中不能轉換到Gameobjects.Player

我的目的是創建2個不同的實例名球員的對象動態。如果在「3」例如有人類型,我想提前

+3

'Object o = name; Player temp =(Player)o;'你認爲這樣做了什麼?如果你回答它,那麼你解決了你的問題。 –

+0

Java很棒,但它不能做魔術!不過,你應該真正修復格式並提供更多信息(請參閱http://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug - 我的應用程序,錯誤) – isnot2bad

回答

2

我想所有你想要的是這樣嗎?

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

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

也許只是

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

代替或者另一種方法是從讀控制檯(或文件)線,並提取nameamountShipString.split功能例如。

編輯:

不能動態地創建實例像你的問題。但是你可以創建數組Player[]這樣

// 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); 
} 

,然後讓第i個球員像這樣(假設類PlayergetName法)

players[i].getName(); 
1

String創建

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

感謝很多無法通過鑄造轉化爲「斯皮勒」。相反,您可以使用Serialization,或者創建一個方法來解析某些給定輸入的對象的屬性。

0

你並不需要一個String轉換到一個對象,因爲String是一個deafault對象,因此不需要投射。你可以做到以下幾點:

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

如果你問自己,爲什麼你的代碼是不工作的方式,它是那是因爲你正嘗試將String鑄造成Player。您的對象o指向String,因此當您嘗試執行(Player)o時,您試圖將字符串強制轉換爲Player,並且它們之間沒有任何關係。