2015-06-15 41 views
0

我真的沒有看到任何回答我的問題,現在我卡住了。它的要點是,我存儲一個HashMap內的向量作爲一個字符串,像這樣:Java HashMap - String to bukkit Vector?怎麼樣?

notes.put(notes.size()+1), player.getLocation().getDirection().toString());

notes是我的HashMap的名字。由於HashMaps看起來只存儲字符串,我需要一種方法將其轉換回Vector。

在我的代碼之後,我後來實施載體是這樣的:

`player.getLocation().setDirection(vector);` 

當我想不出圍繞轉換的方式,我想計算的方向,像這樣面對這樣的數學方法:

`double pit = ((parsed[4]+ 90) * Math.PI)/180; 
double ya = ((parsed[3]+ 90) * Math.PI)/180; 
double newX = Math.sin(pit) * Math.cos(ya); 
double newY = Math.sin(pit) * Math.sin(ya); 
double newZ = Math.cos(pit); 
Vector vector = new Vector(newX, newZ, newY);` 

pit是所述間距和ya作爲偏航。 parsed[3]parsed[4]只是我原來的球員和球員的偏航。再次,這不起作用,並將此錯誤發送到服務器控制檯。 [ERROR]: null。總之,我只是想要一種將字符串轉換爲矢量的方式。我不想用數學方式去做,但如果我沒有選擇,那就這樣吧。讚賞任何幫助和建設性的批評;提前致謝!作爲一個方面說明:我對Java相當陌生,但我有C和JavaScript經驗,所以很多東西都是我熟悉的。

+5

HashMaps可以存儲矢量爲值... –

+0

哦,對,我記得。我使用'HashMap ',我只使用一個。 @Juned Ahsan – Brendan

+0

是啊...... _why_?不要打擾轉換。使用'HashMap '。 –

回答

3

HashMaps不限於存儲字符串。它們可以存儲任何對象,包括Vectors

Map<Integer, Vector> myMap = new HashMap<Integer, Vector>(); 

所以,與其擔心一個字符串轉換爲一個矢量,你可以簡單地存儲載體在你的HashMap

Map<Integer, Vector> notes = new HashMap<Integer, Vector>(); 

//add a vector to the map 
notes.put(notes.size() + 1, player.getLocation().getDirection()); 

//get a vector out of the map 
Vector playerVector = notes.get(notes.size()); 

另外,與你的方式」重新目前正在寫它,你可以簡單地使用ArrayList

List<Vector> notes = new ArrayList<Vector>(); 

//add a vector to the array 
notes.add(player.getLocation().getDirection()); 

//get a vector out of the map 
Vector playerVector = notes.get(notes.size()); 

如果你真的想字符串更改爲載體出於某種原因,Y ou可以使用

//get the x, y, and z values of the vector as an Array 
String[] components = vectorString.split(","); 

//components[0] will be the x value, [1] will be y, and [2] will be z. 
double x = Double.valueOf(components[0]); 
double y = Double.valueOf(components[1]); 
double z = Double.valueOf(components[2]); 

//construct the vector using the components 
Vector myVector = new Vector(x, y, z);