[英]Java - Sorting a 2D Array
I'm trying to get this code to loop through the nested string/array and output the value based on the given input value. 我正在尝试使此代码遍历嵌套的字符串/数组,并根据给定的输入值输出值。
// wepName - {"Weapon Name Here", "Player Damage", "Block Damage", "Range"}
String[] weapon_44Magnum = {"44 Magnum", "150", "50", "45"};
String[] weapon_airFilterLandMine = {"Air Filter Land Mine", "300", "200", "5"};
String[] weapon_huntingRifle = {"Hunting Rifle", "125", "50", "100"};
//Nested string arrays
public String[] string_allWeapons[] = {weapon_44Magnum,weapon_airFilterLandMine,weapon_huntingRifle};
public String GetPlayerDamage(String weaponName) {
// Declaring var
String ret = "-1";
for (int j = 0; j < string_allWeapons[0].length; j++) {
ret = string_allWeapons[j][1] = ret;
System.out.println(string_allWeapons[j][1]);
}
return ret;
}
Any solutions? 有什么办法吗?
You could add an if
to check which array is required by the parameter, then add a second loop
. 您可以添加
if
来检查参数需要哪个数组,然后添加第二个loop
。
public class Stuff {
// wepName - {"Weapon Name Here", "Player Damage", "Block Damage", "Range"}
String[] weapon_44Magnum = {"44 Magnum", "150", "50", "45"};
String[] weapon_airFilterLandMine = {"Air Filter Land Mine", "300", "200", "5"};
String[] weapon_huntingRifle = {"Hunting Rifle", "125", "50", "100"};
//Nested string arrays
String[][] string_allWeapons = {weapon_44Magnum,weapon_airFilterLandMine,weapon_huntingRifle};
public static void main(String[] args) {
new Stuff().getPlayerDamage("44 Magnum");
}
public String getPlayerDamage(String weaponName) {
String ret = "-1";
for (int i = 0; i < string_allWeapons.length; i++) {
if(string_allWeapons[i][0].equals(weaponName)){
ret="";
for (int j = 1; j < string_allWeapons[i].length; j++) {
ret += " "+string_allWeapons[i][j];
}
System.out.println(ret);
return ret;
}
}
return ret;
}
}
My first solution would be making a new class called "Weapon" with those variables. 我的第一个解决方案是使用这些变量创建一个名为“武器”的新类。 Its just a lot easier to keep track of.
它只是更容易跟踪。 Then you could make a 1-D array of weapons and use getters and setters to get the value of each weapon :).
然后,您可以制作一维武器阵列,并使用吸气剂和装气剂来获取每种武器的价值:)。 Then you could loop through the array and do something like this:
然后,您可以遍历数组并执行以下操作:
if(weapon.getName().equals(weaponName)){
System.out.println(weapon.getPlayerDamage());
return weapon.getPlayerDamage();
}
I am still getting used to this code block thing...Anyways making a new class is the way to go. 我仍然习惯于使用此代码块...无论如何都要创建一个新类。 Hopefully this helps.
希望这会有所帮助。 Let me know if you need any clarification :)
让我知道您是否需要任何澄清:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.