我正在尝试创建一种方法,获取分配给字符串中字符的 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/