Hi friend! Today, we learn to make your game make smart choices based on what players type!
Plan
- Methods:
Scanner.next(),Scanner.nextLine(),String.equals(),if-else if-else,Logical operators (&&, ||) - Stretch Methods:
String.trim(),String.toLowerCase()
-
Scanner.next()- Code:
String word = myScanner.next(); - Metaphor: It's like a tiny grabber for just one word.
- Result: If you type "go north",
wordwill be "go". - Why it helps: Gets the first command a player types.
- Code:
-
Scanner.nextLine()- Code:
String sentence = myScanner.nextLine(); - Metaphor: It's like a long grabber for the whole line you type.
- Result: If you type "go north",
sentencewill be "go north". - Why it helps: Gets the full instruction from the player.
- Code:
-
String.equals()- Code:
if (playerMove.equals("walk")) { ... } - Metaphor: It's like matching two Lego bricks to see if they are exactly the same.
- Result: The code inside
ifruns only ifplayerMoveis "walk". - Why it helps: Checks if a player's command matches a known word.
- Code:
-
if-else if-else- Code:
if (score > 10) { ... } else if (score > 5) { ... } else { ... } - Metaphor: It's like choosing different paths at a park based on signs.
- Result: Your game does different actions for different choices.
- Why it helps: Makes your game react differently to many player inputs.
- Code:
-
Logical operators (&&, ||)- Code:
if (age > 10 && hasKey) { ... }orif (rain || snow) { ... } - Metaphor:
&&means "and" (both must be true).||means "or" (one can be true). - Result: Code runs only when ALL things are true (
&&) or if AT LEAST ONE thing is true (||). - Why it helps: Checks many rules at the same time for complex actions.
- Code:
-
Stretch —
String.trim()- Code:
String cleanInput = dirtyInput.trim(); - Metaphor: It's like wiping dirt (extra spaces) off your shoes.
- Result: " hello " becomes "hello".
- Why it helps: Your game understands commands even with extra spaces.
- Code:
-
Stretch —
String.toLowerCase()- Code:
String smallInput = myInput.toLowerCase(); - Metaphor: It's like turning all big letters into small letters.
- Result: "YES" or "Yes" becomes "yes".
- Why it helps: Your game understands "go" no matter how the player types it.
- Code:
Your turn!
- Make a new Java file named
ChoicesGame.java. - Inside, make a
Scannerand ask: "What do you want to do (explore/fight/rest)?" - Read the player's full answer using
nextLine(). - Use
trim()andtoLowerCase()on their answer. - Use an
if-else if-elsewithequals()to check if they typed "explore", "fight", or "rest". - For "explore", use
&&to also check if they have "torch" (pretendboolean hasTorch = true;). - Print what the game does for each choice!
What did you learn about making choices in code?