索引超出字符数组范围的错误

huangapple go评论74阅读模式
英文:

index out of range error in character array

问题

class Challenge {
  static final int n = 256;
  static char[] count = new char[n];
  String str;
  
  static void charCounter(String str) {
    for(int i = 0; i < str.length(); i++){
      count[str.charAt(i)]++;
    }
  }
  
  public static String firstNonRepeatingLetter(String str) {
    charCounter(str);
    int pos = -1, i;
    for(i = 0; i < str.length(); i++){
      if(count[str.charAt(i)] == 1){
        pos = i;
        break;
      }
    }
    return Character.toString(str.charAt(pos));
  }
}
英文:

Please I am practiceing some java questions. I am trying to return a non repeating character in an integer. I have written my code and it works for some strings but some are bringing out index out of range error. I do no know where I have done something wrong
Here is my code:

class Challenge {
  static final int n = 256;
  static char[] count = new char[n];
  String str;
  
  static void charCounter( String str ) {
    for(int i = 0; i &lt; str.length(); i++){
      count[str.charAt(i)]++;
    }
  }
  
  public static String firstNonRepeatingLetter( String str ) {
    charCounter(str);
    int pos = -1, i;
    for(i = 0; i &lt; str.length(); i++){
      if(count[str.charAt(i)] == 1){
        pos = i;
        break;
      }
    }
    return Character.toString(str.charAt(pos));
  }
}

答案1

得分: 1

你还没有考虑所有字母都重复的情况,比如字符串"ABBA"。

你还没有明确方法在这种情况下应该执行什么操作,但如果返回一个空字符串是可以接受的,你可以将返回语句改为:

if (pos < 0) return "";
return Character.toString(str.charAt(pos));
英文:

You haven't considered what will happen in the case where all letters repeat, for example the string "ABBA".

You haven't specified full what the method is supposed to do in this case, but if returning an empty string is acceptable, you can change the return statement to:

if (pos &lt; 0) return &quot;&quot;;
return Character.toString(str.charAt(pos));

答案2

得分: 0

if count[str.charAt(i)] == 1:
    pos = i
    break

如果您的输入字符串不满足 `count[str.charAt(i)] == 1`。那么 pos 的值将保持为 -1这会导致在返回语句处出错
英文:
if(count[str.charAt(i)] == 1){
        pos = i;
        break;
      }

If your input String do not satisfies count[str.charAt(i)] == 1. Then the pos value would remains -1 -> it would cause the error at return statement

huangapple
  • 本文由 发表于 2020年8月15日 22:46:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/63427287.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定