英文:
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 < 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));
}
}
答案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 < 0) return "";
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论