Почему целое число после помещения в массив меняет значения? - PullRequest
1 голос
/ 03 апреля 2012

РЕШЕНО ЭТО

Я написал программу, которая загружает строки после знака равенства и подсчитывает, сколько раз это было сделано. После подсчета я говорю это, чтобы сказать мне, как большой int. Значение, которое я ищу, равно 3, и оно говорит мне: 3. Затем я изменяю его на строку, значение остается равным трем. Затем я помещаю его в массив 4d, и он говорит мне, что значение равно 2. Что случилось?

Код:

                   int times=0;
                   else if (list.equals("Weapon")) {//If the word weapon is before the = 
                        weapon = value; //take the string after the = and put it into String weapon
                        troopStats[times][1][weaponTimes][0] = weapon;
                        weaponTimes++;
                        System.out.println(weaponTimes+"weapontimes"+times);
                    }

                        weaponTimesStr = Integer.toString(weaponTimes);
                        System.out.println(weaponTimesStr+"string");
                        troopStats[times][1][0][1] = weaponTimesStr;
                        System.out.println(troopStats[times][1][0][1]+"InArray");
                        times++
                        //loops

Выход:

3weapontimes    //Counted the equals sign 3 times, Note that this is from the part of the 
                 omitted code
3string         // Changed the integer to a string and got 3
2InArray        // Put it into an array, and got 2 back

Что происходит?

(я знаю, что мог бы просто добавить 1 к значению, но позже я хочу использовать этот код для неизвестного количества вещей)

Чтобы помочь, я разместил весь код:

public class TroopLoader {
    static String[][][][] troopStats;
    static int times = 0;
    static int weaponTimes = 0;
    static int armorTimes = 0;
    static int animalTimes = 0;
    static String weaponTimesStr;
    static String armorTimesStr;
    static String animalTimesStr;
    static String troop;
    static String weapon;
    static String armor;
    static String animal;
    static String speed;
    static int total = 0;

    /*
     * [][][]
     * 
     * [total number of troops (total)]
     * 
     * [stats] 0= name 1= weapon 2= armor 3= animal 4= speed
     * 
     * [different things within stat]
     */

    public void readTroop() {

        File file = new File("resources/objects/troops.txt");
        BufferedReader reader = null;

        try {
            reader = new BufferedReader(new FileReader(file));
            String text = null;

            // repeat until all lines is read
            while ((text = reader.readLine()) != null) {
                StringTokenizer troops = new StringTokenizer(text, "=");
                if (troops.countTokens() == 2) {
                    String list = troops.nextToken();

                    if (list.equals("Troop")) {
                        total++;
                    }

                    else {

                    }
                } else {

                }

            }
            troopStats = new String[total][5][10][2];

        }

        catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        File file2 = new File("resources/objects/troops.txt");
        BufferedReader reader2 = null;

        try {
            reader2 = new BufferedReader(new FileReader(file2));
            String text = null;

            // repeat until all lines is read
            while ((text = reader2.readLine()) != null) {
                StringTokenizer troops = new StringTokenizer(text, "=");
                if (troops.countTokens() == 2) {
                    String list = troops.nextToken();
                    String value = troops.nextToken();

                    if (list.equals("Troop")) {
                        troop = value;

                        troopStats[times][0][0][0] = troop;
                    }

                    else if (list.equals("Weapon")) {
                        weapon = value;
                        troopStats[times][1][weaponTimes][0] = weapon;
                        weaponTimes++;
                        System.out.println(weaponTimes+"weapontimes"+times);
                    }

                    else if (list.equals("Armor")) {

                        armor = value;

                        troopStats[times][2][armorTimes][0] = armor;
                        armorTimes++;
                    }

                    else if (list.equals("Animal")) {

                        animal = value;

                        troopStats[times][3][animalTimes][0] = animal;
                        animalTimes++;
                    }

                    else if (list.equals("Speed")) {

                        speed = value;

                        troopStats[times][4][0][0] = speed;

                    }

                    else if (list.equals("Done")) {
                        weaponTimesStr = Integer.toString(weaponTimes);
                        System.out.println(weaponTimesStr+"string");
                        armorTimesStr = Integer.toString(armorTimes);
                        animalTimesStr = Integer.toString(animalTimes);
                        troopStats[times][1][0][1] = weaponTimesStr;
                        troopStats[times][1][0][1] = armorTimesStr;
                        troopStats[times][1][0][1] = animalTimesStr;
                        System.out.println(troopStats[times][1][0][1]+"InArray"+times);
                        times++;
                        troop = "";
                        weapon = "";
                        armor = "";
                        animal = "";
                        speed = "";
                        weaponTimes = 0;
                        armorTimes = 0;
                        animalTimes = 0;

                    }

                    else {

                    }

                } else {

                }

            }

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        finally {
            try {
                if (reader2 != null) {
                    reader2.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

В более ранней части кода у меня была программа для сохранения значения в местоположении в массиве с помощью переменной armsTimes, а не хранения переменной armsTimes. Моя ошибка, извините за трату вашего времени.

Ответы [ 3 ]

3 голосов
/ 03 апреля 2012

Следующее:

public class Foo {
  public static void main(String[] args) {
    String[][][][] troopStats = new String[2][2][2][2];
    String weaponTimesStr = Integer.toString(3);
    System.out.println(weaponTimesStr+"string");
    troopStats[0][1][0][1] = weaponTimesStr;
    // You said in a comment that 'times' is equal to 0 in this case so have subbed that in
    System.out.println(troopStats[0][1][0][1]+"InArray");
  }
}

Дает ожидаемый результат:

3string
3InArray
3 голосов
/ 03 апреля 2012

Я написал SSCCE с тем, что вы опубликовали, и он напечатает то, что вы ожидаете:

public static void main(String[] args) {
    String[][][][] troopStats = new String[4][4][4][4];
    int times = 2;
    int weaponTimes = 3;
    String weaponTimesStr = Integer.toString(weaponTimes);
    System.out.println(weaponTimesStr + "string"); //prints 3string
    troopStats[times][1][0][1] = weaponTimesStr;
    System.out.println(troopStats[times][1][0][1] + "InArray"); //prints 3InArray
}

Так что проблема, скорее всего, в чем-то / где-то еще.

0 голосов
/ 03 апреля 2012

Извините, что я потратил впустую ваше время, моя ошибка была в том, что я хранил значения в массиве, используя значения WeaponeTimes, а не хранил в файле WeapTimes.

troopStats[times][1][weaponTimes][0] = weapon;

Это была ошибка.

...