我有這個任務需要
撰寫一個接受字串引數的方法。如果字串有一個雙字母(即連續兩次包含相同的字母),那么它應該回傳真。否則,它應該回傳false。
此方法必須命名為 hasRepeat() 并具有 String 引數。此方法必須回傳一個布林值。
但是,當我簽入我的代碼時,我沒有通過一些測驗。
它說false當沒有重復的字母時它不會回傳。
這是我的代碼:
public static boolean hasRepeat(String word) {
for (int i = 0; i < word.length(); i ) {
for (int j = i 1; j < word.length(); j ) {
if (word.substring(i, i 1).equals(word.substring(i, j))) {
return true;
}
}
}
return false;
}

uj5u.com熱心網友回復:
不需要嵌套回圈。我們所要做的就是檢查當前字符是否等于前一個:
public static boolean hasRepeat(String word)
{
// hasRepeat is a public method; we shoud be ready for any input
if (word == null)
return false;
// here we start from 1: there's no previous char for charAt(0)
for (int i = 1; i < word.length(); i)
if (word.charAt(i - 1) == word.charAt(i))
return true;
return false;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/344375.html
下一篇:如何向陣列添加越來越多的內容
