問題:我在Java中玩耍,我試圖計算字符串中連續的「字符」。Java字符串:檢查連續的字母或數字
實施例:
Scanner in = new Scanner(System.in);
int n = in.nextInt();
String binaryString = Integer.toBinaryString(n);
上面的代碼返回輸入的整數值的二進制字符串。如果我們輸入數字5,這將返回:101
我現在希望遍歷字符串並檢查字符串中是否有任何連續的1。
for (int i = 0; i < binaryString.lenth(); i++)
{
// code comes here...
}
我不知道該如何檢查。我曾嘗試以下:
for (int i = 0; i < binaryString.length(); i++)
{
char charAtPos = binaryString.charAt(i);
char charAtNextPos = binaryString.charAt(i+1);
if (charAtPos == '1')
{
if (charAtPos == charAtNextPos)
{
consecutive += 1;
}
}
}
但這顯然拋出作爲的ArrayIndexOutOfBounds將i+1
產生一個數比陣列長度大。
非常感謝您的回答。
歐文
那麼在你的condidtion中如何使用binaryString.length() - 1? :) – kolboc