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

问题描述:

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

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; 
    } 
} 
+0

最后一个字符是索引'长度() - 1',因为第一索引是'0'。 – Gendarme

+0

当您尝试访问不存在的数组索引时,会发生Java索引超出范围错误。请注意,Java数组以索引0开始很重要,请参阅您是否可以根据此信息弄清楚它。我不想放弃答案......它不会帮助你学习。 –

+0

int j = input.length() - 1; – Abdelhak

错误发生在第21行:int j = input.length(),如评论,JAVA提到的其他人,大多数编程语言,索引字符串和数组类型由0索引 - 从零开始。因此,你必须要么1)开始在在0或2)计数停止计数一低于所述字符串的长度(阵列),这就是为什么线21个需要是以下之一:

int j = input.length()-1;

或作为你解决了它的使用方法1:

设置int j=0;