[英]Java How to avoid String Index out of Bounds
我有以下任務要做:
如果字符串“ cat”和“ dog”在給定的字符串中出現相同的次數,則返回true。
catDog(“ catdog”)→true catDog(“ catcat”)→false catDog(“ 1cat1cadodog”)→true
我的代碼:
public boolean catDog(String str) {
int catC = 0;
int dogC = 0;
if(str.length() < 3) return true;
for(int i = 0; i < str.length(); i++){
if(str.charAt(i) == 'd' && str.charAt(i+1) == 'o' && str.charAt(i+2) == 'g'){
dogC++;
}else if(str.charAt(i) == 'c' && str.charAt(i+1) == 'a' &&
str.charAt(i+2) == 't'){
catC++;
}
}
if(catC == dogC) return true;
return false;
}
但是對於catDog("catxdogxdogxca")
→ false
我得到了StringIndexOutOfBoundsException
。 我知道它是由if子句在嘗試檢查charAt(i+2)
等於t時引起的。 如何避免這種情況? 謝謝問候:)
for(int i = 0; i < str.length(); i++){ // you problem lies here
if(str.charAt(i) == 'd' && str.charAt(i+1) == 'o' && str.charAt(i+2) == 'g')
您正在使用i < str.length()
作為循環終止條件,但是您正在使用str.charAt(i+1)
和str.charAt(i+2)
由於您需要訪問i+2
,因此應該將范圍限制為i < str.length() - 2
。
for(int i = 0, len = str.length - 2; i < len; i++)
// avoid calculating each time by using len in initialising phase;
邏輯存在問題,條件語句試圖訪問超出字符串大小的字符。
輸入: catxdogxdogxca在末尾有ca ,這就是為什么執行else塊並試圖獲取i + 3處存在的字符(輸入中不存在)的原因。 這就是為什么您看到java.lang.StringIndexOutOfBoundsException的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.