我目前正試圖弄清楚為什么以 x 結尾的案例會導致 OutOfBoundsError,如下面的 3 個測驗案例。
任務是計算字串中'x'的數量;如果“x”后面跟著另一個“x”,則計為雙倍。
謝謝,如果您能提供幫助,我將不勝感激。
public class CountXWithDubs {
/**
* Count the number of 'x's in the string. Any 'x' that is followed by
* another 'x' should count double (e.g. "axxbxc" -> 4)
*
* @param x a string.
* @return the count of x's.
*/
public static int countXWithDubs(String s) {
if(s == null || s.isEmpty()) {
return 0;
}
int count = 0;
if(s.charAt(0) == 'x') {
if(s.charAt(1) == 'x') {
count = 2;
}
else {
count ;
}
}
return count countXWithDubs(s.substring(1));
}
@Test
public void testXSEnd() {
assertEquals("Incorrect result with x at end", 2,
countXWithDubs("abxcdx"));
}
@Test
public void testDoubleXEnd() {
assertEquals("Incorrect result with double x at end", 4,
countXWithDubs("abxcdxx"));
}
@Test
public void testBunchOfXs() {
assertEquals("Incorrect result with bunch of x's", 13,
countXWithDubs("xxxaxbxxcxdxx"));
}
}
uj5u.com熱心網友回復:
s
如果字串的長度為1,就會出現OutOfBoundsError ,然后s.charAt(1)
會導致這個錯誤,所以你需要在訪問下一個元素時檢查長度
if(s.charAt(0) == 'x') {
if(s.length()>1 &&s.charAt(1) == 'x') {
count = 2;
}else {
count ;
}
}
uj5u.com熱心網友回復:
public static int countX(String str){
if(str == null || str.isEmpty()) {
return 0;
}
int currentPos = 0;
int len = str.length();
int count = 0;
if(str.charAt(currentPos) == 'x'){
if(currentPos 1 < len && str.charAt(currentPos 1)=='x'){
count =2;
}
else{
count =1;
}
}
return count countX(str.substring(1));
}
試試這段代碼,當我們只有一個字符時,問題會在最后一次迭代中以 charAt(1) 出現。添加另一個 if 條件將解決此問題
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/507825.html