字符串索引超出方法范围:Java

时间:2016-10-11 00:56:38

标签: java indexing

我正在为我的类编写一些代码,我遇到了这个错误,字符串索引超出了范围。我检查了它是否可能是string = null但事实并非如此。我猜测它与方法中的if语句有关,但我无法找到如何在任何地方修复它。非常感谢任何帮助,非常感谢!

import java.util.*;
public class Occurences { 
   public static void main(String[] args) {
      int check = 0;
         char characterInput = ' ';
         do {
            Scanner scan = new Scanner(System.in);
            System.out.println("Please enter a string: ");
            String input = scan.next();
            System.out.println("Enter a character to find it's occurence in the string: ");
            characterInput = scan.next().charAt(0);
            int i = count(input, characterInput);

            System.out.println(characterInput + ", is in " + input + ", " + i + " times.");
            System.out.println("To continue enter any number, to exit enter -1: ");
            check = scan.nextInt();
         } while (check != -1);
    }
   public static int count(String input, char characterInput) {
      int cnt = 0;
      int j = input.length();
      while (j > 0) { 
         if (input.charAt(j) == characterInput) { 
         cnt += 1;
         }
         j--;
         }
     return cnt;
   }
}

1 个答案:

答案 0 :(得分:0)

错误发生在第21行:int j = input.length(),正如其他人在评论,java和大多数编程语言中提到的那样,索引字符串和数组类型通过零索引 - 从零开始。所以你必须要么1)从0开始计数,要么2)停止计数比字符串(数组)的长度少一个,这就是为什么第21行必须是:

int j = input.length()-1;

或使用方法1解决它:

设置int j=0;