简体   繁体   中英

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 .

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM