Lesson 6.5 · Write it
Check a nickname
A functionPython or Java12 tests, 8 of them hidden
On a phone? Put the lines in order instead
A game shows each player's nickname above their character. Before it saves a nickname, it checks it. Write a function that returns whether a nickname is allowed.
- A nickname is allowed when it has from 3 to 12 characters and has no space in it.
- Return
Truewhen it is allowed andFalsewhen it is not (trueandfalsein Java). - The nickname is made of letters, digits and spaces only. It can be empty.
Only the value your function returns is checked.
def valid_nickname(name: str) -> bool
Examples
Your function is tested on 12 cases: the 4 examples below, and 8 hidden ones that check the rules above.
- valid_nickname("Kai") should return True: exactly 3 characters, the shortest allowed (rule 1)
- valid_nickname("Lumi2026Star") should return True: exactly 12 characters, the longest allowed (rule 1)
- valid_nickname("Jo") should return False: only 2 characters (rule 1)
- valid_nickname("Red Fox") should return False: the right length, but with a space (rule 1)
public static boolean validNickname(String name)
Running Java here comes later. You can put this answer's lines in order instead. You can still write your Java answer (it stays while this page is open) and compare it with our worked solution. Or try this exercise in Python.Checking whether Java answers can run here.
Examples
Your function is tested on 12 cases: the 4 examples below, and 8 hidden ones that check the rules above.
- validNickname("Kai") should return true: exactly 3 characters, the shortest allowed (rule 1)
- validNickname("Lumi2026Star") should return true: exactly 12 characters, the longest allowed (rule 1)
- validNickname("Jo") should return false: only 2 characters (rule 1)
- validNickname("Red Fox") should return false: the right length, but with a space (rule 1)