当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Switch statement inside for loop does not increment "i" correctly

问题描述:

I have the following code:

String everything = sb.toString(); //stores all the data from the input file into a string

String replaceAll = everything.replaceAll("\\s", "");

int charCount = replaceAll.length(); //charCount is 147

char arr[] = replaceAll.toCharArray();

for (int i = 0; i < arr.length; i++) {

switch (arr[i]) {

case 'E': {

fridge[Character.getNumericValue(arr[(i + 1)])].is_empty();

}

break;

case 'F': {

fridge[Character.getNumericValue(arr[(i + 2)])].find_it(Character.getNumericValue(arr[(i + 1)]));

}

break;

case 'C': {

fridge[Character.getNumericValue(arr[(i + 3)])].combineFridge(fridge[Character.getNumericValue(arr[(i + 2)])], fridge[Character

.getNumericValue(arr[(i + 1)])]);

}

break;

case 'M': {

fridge[Character.getNumericValue(arr[(i + 3)])].commonItems(fridge[Character.getNumericValue(arr[(i + 2)])], fridge[Character

.getNumericValue(arr[(i + 1)])]);

}

break;

case 'I': {

fridge[Character.getNumericValue(arr[(i + 2)])].insertItem(Character.getNumericValue((i + 1)));

}

break;

case 'D': {

fridge[Character.getNumericValue(arr[(i + 2)])].delete_item(Character.getNumericValue((i + 1)));

}

break;

case 'O': {

fridge[Character.getNumericValue(arr[(i + 1)])].outputRefrigerator();

}

break;

}

}

The char array has 147 elements, and there's a number after each letter.

Each letter activates a method, followed by 1-3 parameters (numbers).

However, inside the for loop, I am getting a -1 value and sometimes random large numbers (all my numbers are positive and less than 12).

If I manually call any method outside the for loop for example:

fridge[Character.getNumericValue(arr[0].insertItem(Character.getNumericValue(arr[1]);, everything works fine and the value which is at arr[1] (which is 1) is stored at this.fridgeItems (an int[] array).

Why is this happening? I know it's a problem with either the switch statement or the for loop but I can't really tell.

网友答案:

Check your indices. In your code you are accessing elements from arr by i + 1 and i + 2 index. If your loop iterates more than n - 2 times, you will have IndexOutOfBoundException.

By the way, you need to increment i in your switch statement to skip "used" characters from the input array.

网友答案:

Your code is "not increment i correctly", because there is no code in the switch statement to actually increment i.

You should do something like this:

case 'C':
    fridge[Character.getNumericValue(arr[i + 3])]
            .combineFridge(fridge[Character.getNumericValue(arr[i + 2])],
                           fridge[Character.getNumericValue(arr[i + 1])]);
    i += 3;
    break;
分享给朋友:
您可能感兴趣的文章:
随机阅读: