重要なお知らせ

「教えて! goo」は2025年9月17日(水)をもちまして、サービスを終了いたします。詳細はこちら>

【GOLF me!】初月無料お試し

同じ文字が連続して並ぶ時、2回目以降の同じ文字を削除して出力する以下のコード(例"cat cat hat cat" -> "cat hat cat") の穴埋め問題3問(charAtメソッドを使うよう指示)で、以下のように回答したのですが、エラーになりました。
9行目while ( inputString.charAt(stringIndex) != 0000)
の部分にエラーがあるようです。スペースに至るまでの文字 (次の文字がスペースになるまでchatAtメソッドを使う)を取り込もうと思ったのですが、どう改善したら良いでしょうか。


inputString = inputString.trim(); // Remove any leading and trailing blanks
String result = "", currentWord = "", nextWord = "";
int stringLength = inputString.length(); // Length of the input string
int stringIndex = 0; // Index for input string

while (stringIndex < stringLength) {

// (Question1) Get the next word in inputString
while ( inputString.charAt(stringIndex) != 0000){

nextWord = nextWord + inputString.charAt(stringIndex);
stringIndex++;
}
// (Question2) Check if nextWord is the same as currentWord
if ( nextWord != currentWord ) {

result = result + nextWord;//(Question3)
}

stringIndex++;
currentWord = nextWord;
nextWord = "";
}

return result.trim(); // Remove any leading and trailing blanks from result

A 回答 (1件)

色々問題のあるソースの様ですが、


ご質問の内容にだけ回答すると

メソッド charAt は char を返すので
https://docs.oracle.com/javase/jp/10/docs/api/ja …
比較対象も char 型の形式で書きましょう
https://docs.oracle.com/javase/specs/jls/se10/ht …
    • good
    • 0

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!