id/email
password
forgot password | create account
about | help | code help+videos | done | prefs
CodingBat code practice

 

apcsaLoopsSameCharacter


Given an input String, return true if the String is made up of only the same character, repeated over and over. Return false if the input has any variety of characters. Precondition: str will have at least one character.


HINT: This problem is a classic use case of what could be called the "assume, then disprove" type of problem.  Many times in programming, an output checks for "at least one of" or "none of" something.  A useful strategy in these cases is to assume the answer is that all the inputs will match a pattern the same way, with a boolean variable that can only change in one direction (true to false, or false to true) during the checking process.  Since it only takes one different character to return false, this variable could reasonably be assumed to start as true and then turn to false during the loop.  Or in this case, you could early return false as soon as you found a different character.

As far as what to check, you could either assume that all characters in the String are equal to the first character (index 0), or that all neighboring pairs of characters are equal to one another.  Those are two different ways of making sure that you get all the necessary comparisons.

ADVANCED CHALLENGE: try using the replace method of the String class to replace all instances of one search String with a replacement String.  The version of replace you might want here is replace(CharSequence target, CharSequence replacement).  Which doesn't look useful until you know that a String is-a CharSequence.  (Technically CharSequence is an interface not a class, and interfaces are no longer taught in AP CSA, but that rabbit hole is not helpful here.)  The replace method can be used in a clever way to automatically find how many times a substring occurs, by comparing the length of the original to the length of the version with replacements, so long as the replacements are of a different length than the original.

apcsaLoopsSameCharacter("aaa") → true
apcsaLoopsSameCharacter("Aaa") → false
apcsaLoopsSameCharacter("333333y3333") → false

...Save, Compile, Run (ctrl-enter)

public boolean apcsaLoopsSameCharacter(String str) { }

Editor font size %:
Shorter output


Forget It! -- delete my code for this problem

Progress graphs:
 Your progress graph for this problem
 Random user progress graph for this problem
 Random Epic Progress Graph

Java Help

Misc Code Practice

Difficulty: 210

Copyright Nick Parlante 2017 - privacy