java - 为什么 for 循环索引不能正常工作?

标签 java arrays for-loop while-loop

我正在尝试创建一种方法,获取分配给字符串中字符的 int 值,将它们相加并返回总数。

由于某种原因,嵌套循环似乎无法正常工作。

public static int tap_counter(String type) {

    String[] type_array = type.split("");

    String[] example_letters = new String[] {"A","B"}; 

    int total = 0;

    for(int i=0; i < type_array.length;i++){  
        for(int j=0; type_array[i] != standard_letters[j]; j++) 
        {
          if(type_array[i] == "A") total += 1;
          else if(type_array[i] == "B") total += 2;
        }
     }
    return total;
}

它适用于单字符字符串,但对于多元素字符串,我遇到了 OutOfBounds 异常。

例如,对于输入“AB”:

  • 预期输出为 3;

  • 实际输出:java.lang.ArrayIndexOutOfBoundsException:索引 2 超出长度 2 的范围。

最佳答案

希望这有帮助:

public static int tap_counter(String type) {

String[] type_array = type.split("");

String[] example_letters = new String[] {"A","B"}; 

int total = 0;

for(int i=0; i < type_array.length;i++){  
    for(int j=0; j < example_letters.length; j++) 
    {
        System.out.println("Trying to match " + type_array[i] + " and " + example_letters[j]);
        if(type_array[i] == example_letters[j] {
              total += (j+1); //j index is one less than the value you wish to assign
              System.out.println("Match found. New total is:" + total)
              break; //exit innermost for loop
        }
    }
 }
return total;

}

关于java - 为什么 for 循环索引不能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58640054/

相关文章:

java - 打印机如何不覆盖

php - 处理数组并插入mysql表中

python - 使用 python 中的列表理解更改列表值

java - 抛出异常后执行代码

java - 在确保字符串是有效的 double 值时,如何解释 ","和 "."?

java - 在jTextfield中显示jTable(char)数据

c - 小型(ish)二维阵列的段错误

c - 我如何在 C 中使用指针的指针?

java - 错误地使用for循环

python - 嵌套 for 循环的计算复杂度