【问题标题】:String index out of range inside of a method: Java方法内的字符串索引超出范围:Java
【发布时间】:2016-10-11 00:56:37
【问题描述】:

我正在为我的班级编写一些代码,我遇到了这个错误,字符串索引超出范围。我检查了它是否可能是 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;
   }
}

【问题讨论】:

  • 最后一个字符在索引length()-1上,因为第一个索引是0。
  • 当您尝试访问不存在的数组索引时,会发生 Java 索引超出范围错误。重要的是要注意 Java 数组以索引 0 开头。看看你是否能根据这个信息弄清楚。我不想泄露答案......它不会帮助你学习。
  • int j = input.length()-1;
  • 感谢所有 cmets,我最终将 j 切换为 0 并递增,但我知道错误发生在哪里。
  • @GabrielTomasetto,请参阅下面的答案,我解释了您所做的工作的原因。如果我的回答有助于为您解释,请考虑支持并接受它作为答案。 =] 谢谢!

标签: java indexing


【解决方案1】:

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

int j = input.length()-1;

或者当你使用方法 1 解决它时:

设置int j=0;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-01
    • 2012-01-15
    • 2014-06-12
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    • 2010-10-31
    相关资源
    最近更新 更多