Tech
CodeHS 4.7.11 Rock Paper Scissors: Complete Java Guide
CodeHS 4.7.11 Rock Paper Scissors is a Java programming exercise in which students build an interactive game against a computer.
CodeHS 4.7.11 Rock Paper Scissors is a Java programming exercise in which students build an interactive game against a computer. The program accepts a player’s choice, generates a random computer move, determines the winner, and continues until the player chooses to stop.
The exercise teaches essential Java programming concepts, including conditional statements, loops, methods, string comparisons, and random number generation. It also helps students understand how several programming concepts work together in a complete application.
According to the official CodeHS Introduction to Java course outline, exercise 4.7.11, titled Rock, Paper, Scissors!, appears in the section on Class Methods and Class Variables. It follows exercise 4.7.10, Rock, Paper, Scissors: Get Winner, which focuses on determining the winner of a round.
This guide explains the assignment requirements, game logic, a complete Java implementation, common coding mistakes, and practical ways to test the program.
What Is CodeHS 4.7.11 Rock Paper Scissors?
CodeHS 4.7.11 is an interactive Java exercise designed to strengthen students’ understanding of program control flow and reusable methods.
Instead of simply printing information or performing a calculation, students create a game that responds to user input and produces different results depending on the choices made.
The project follows the familiar rules of Rock, Paper, Scissors:
- Rock beats scissors: Rock wins because it crushes scissors.
- Paper beats rock: Paper wins because it covers rock.
- Scissors beat paper: Scissors win because they cut paper.
- Matching choices produce a tie: Neither player wins when both select the same option.
These rules are straightforward, but converting them into reliable Java code requires careful use of conditions and comparisons.
Where Does Exercise 4.7.11 Appear in CodeHS?
The official CodeHS curriculum places the exercise in Lesson 4.7, Class Methods and Class Variables.
| Exercise | Title | Main Learning Focus |
|---|---|---|
| 4.7.5 | Using Randomizer | Generating random values |
| 4.7.9 | Circle Area, another way | Working with class methods |
| 4.7.10 | Rock, Paper, Scissors: Get Winner | Implementing winner determination |
| 4.7.11 | Rock, Paper, Scissors! | Building the interactive game |
Source: CodeHS Introduction to Java curriculum.
The relationship between exercises 4.7.10 and 4.7.11 is especially important. The earlier exercise introduces the method for determining the winner, while the following exercise uses that logic within a playable program.
CodeHS 4.7.11 Rock Paper Scissors Requirements
The main objective is to create a working Rock, Paper, Scissors game that allows a user to play against a computer.
The CodeHS demonstration describes a program that asks the user to choose a move, randomly selects a computer move, displays the result, and continues until the user presses Enter without entering a choice.
A suitable implementation therefore needs to perform several operations:
- Ask the player to enter rock, paper, or scissors.
- Generate a random move for the computer.
- Compare the two choices.
- Determine whether the user wins, the computer wins, or the round ends in a tie.
- Display the player’s move, the computer’s move, and the result.
- Repeat the game until the user submits an empty response.
A well-designed version can also handle invalid input without ending unexpectedly.
Important: CodeHS may provide starter code, required method names, or specific output expectations. Students should follow the instructions visible in their own assignment when these differ from the illustrative implementation below.
Understanding the Game Logic Before Writing Code
The most important part of the exercise is determining the winner correctly.
There are nine possible combinations of moves because each player has three choices.
Rock Paper Scissors Outcome Table
| User Choice | Computer Choice | Result |
|---|---|---|
| Rock | Rock | Tie |
| Rock | Paper | Computer wins |
| Rock | Scissors | User wins |
| Paper | Rock | User wins |
| Paper | Paper | Tie |
| Paper | Scissors | Computer wins |
| Scissors | Rock | Computer wins |
| Scissors | Paper | User wins |
| Scissors | Scissors | Tie |
Understanding this table makes the programming logic easier to implement.
First, check whether both moves are identical. If they match, the result is a tie.
Next, identify the three situations in which the user wins. Any remaining combination of valid, different moves must result in a computer victory.
This approach avoids unnecessarily repeating all nine combinations in separate conditional statements.
Complete Java Code Example for CodeHS 4.7.11
The following example demonstrates a complete Rock, Paper, Scissors game using the CodeHS ConsoleProgram and Randomizer classes.
It includes a reusable getWinner() method, input validation, random computer selections, and a loop that continues until the player presses Enter.
public class RockPaperScissors extends ConsoleProgram
{
private static final String ROCK = "rock";
private static final String PAPER = "paper";
private static final String SCISSORS = "scissors";
public void run()
{
while (true)
{
String user = readLine(
"Enter your choice (rock, paper, or scissors): "
);
if (user == null || user.trim().isEmpty())
{
System.out.println("Thanks for playing!");
break;
}
user = user.trim().toLowerCase();
if (!isValidChoice(user))
{
System.out.println(
"Please enter rock, paper, or scissors."
);
continue;
}
int randomNumber = Randomizer.nextInt(1, 3);
String computer;
if (randomNumber == 1)
{
computer = ROCK;
}
else if (randomNumber == 2)
{
computer = PAPER;
}
else
{
computer = SCISSORS;
}
System.out.println("User: " + user);
System.out.println("Computer: " + computer);
System.out.println(getWinner(user, computer));
}
}
private boolean isValidChoice(String move)
{
return move.equals(ROCK)
|| move.equals(PAPER)
|| move.equals(SCISSORS);
}
private String getWinner(String user, String computer)
{
if (user.equals(computer))
{
return "Tie";
}
if ((user.equals(ROCK)
&& computer.equals(SCISSORS))
|| (user.equals(PAPER)
&& computer.equals(ROCK))
|| (user.equals(SCISSORS)
&& computer.equals(PAPER)))
{
return "User wins!";
}
return "Computer wins!";
}
}
This is an educational implementation of the exercise, not a verified copy of an official CodeHS solution or a guarantee of passing every assignment-specific automated test.
The code uses programming structures supported by the CodeHS Java Library. The implementation has been checked for Java compilation with equivalent local support classes, although it has not been submitted to the CodeHS assignment grader.
Why This Code Works
The implementation separates the game into three main responsibilities.
The run() method controls the game, receives input, generates a computer move, and displays the outcome.
The isValidChoice() method checks whether the player entered one of the three permitted moves.
The getWinner() method receives both choices and returns the correct result according to the game rules.
Separating responsibilities makes the code easier to read, test, and modify.
Step-by-Step Explanation of the Java Program
1. Defining Constants for the Moves
The program begins by declaring three constants:
private static final String ROCK = "rock";
private static final String PAPER = "paper";
private static final String SCISSORS = "scissors";
A constant stores a value that should not change while the program runs.
Using constants avoids repeatedly typing the same strings throughout the code. It also reduces the risk of inconsistent spelling.
The static keyword makes these variables belong to the class, while final prevents their values from being reassigned.
2. Reading the Player’s Choice
The program asks for input using the readLine() method:
String user = readLine(
"Enter your choice (rock, paper, or scissors): "
);
The response is stored in a string variable named user.
The program then checks whether the player submitted an empty response. If so, it displays a goodbye message and exits the loop.
Otherwise, it normalizes the text:
user = user.trim().toLowerCase();
The trim() method removes leading and trailing whitespace, while toLowerCase() converts uppercase letters to lowercase.
For example, ROCK, Rock, and rock are all converted into rock.
This makes the program more forgiving of ordinary typing differences.
3. Generating the Computer’s Random Choice
Random selection is one of the most important features of the exercise.
The program uses:
int randomNumber = Randomizer.nextInt(1, 3);
According to the official CodeHS Randomizer documentation, the two-argument nextInt(min, max) method generates a random integer between the minimum and maximum values, including both endpoints.
Therefore, this statement can return 1, 2, or 3.
The program then converts the number into a move:
if (randomNumber == 1)
{
computer = ROCK;
}
else if (randomNumber == 2)
{
computer = PAPER;
}
else
{
computer = SCISSORS;
}
Each number represents one possible computer selection.
Since the computer’s move is generated randomly, the outcome can change between executions, even when the player enters the same choice.
4. Comparing Moves Using the getWinner() Method
The getWinner() method is responsible for determining the result.
Its method declaration is:
private String getWinner(String user, String computer)
The method receives two strings: the user’s choice and the computer’s choice.
The first condition checks for a tie:
if (user.equals(computer))
{
return "Tie";
}
If both values are identical, the method immediately returns "Tie".
If the choices differ, the next condition checks whether the user has selected a winning combination.
For example:
user.equals("rock") && computer.equals("scissors")
This condition is true only when the user selects rock and the computer selects scissors.
The complete method checks all three winning combinations. If none applies and the inputs are valid and different, the computer wins.
5. Repeating the Game Using a While Loop
The main game loop begins with:
while (true)
This creates a loop that continues until a statement explicitly stops it.
The program uses break when the player submits an empty response.
It also uses continue when an invalid move is entered. This skips the remainder of the current iteration and returns to the input prompt.
These statements provide two different forms of control:
breakexits the loop.continuestarts the next loop iteration.
Understanding their differences is useful beyond this particular assignment.
Example Output of the Rock Paper Scissors Program
A possible execution of the program looks like this:
Enter your choice (rock, paper, or scissors): rock
User: rock
Computer: scissors
User wins!
Enter your choice (rock, paper, or scissors): paper
User: paper
Computer: scissors
Computer wins!
Enter your choice (rock, paper, or scissors): rock
User: rock
Computer: rock
Tie
Enter your choice (rock, paper, or scissors):
Thanks for playing!
The output demonstrates three different results: a user victory, a computer victory, and a tie.
Because the computer uses random selection, this is only an illustrative session. Actual results will vary.
The important requirement is that the program evaluates whichever combination occurs correctly.
Common CodeHS 4.7.11 Errors and How to Fix Them
Even a relatively short Java program can contain errors that prevent it from compiling or producing the expected results.
The following problems are particularly relevant to this exercise.
Using == Instead of equals() for Strings
A common beginner mistake is comparing Java strings using the == operator:
if (user == "rock")
This is not the correct way to compare the text content of strings.
The == operator checks whether two object references identify the same object. It does not reliably compare the characters stored in separate string objects.
Use:
if (user.equals("rock"))
The equals() method checks whether the two strings contain the same characters.
Forgetting to Handle Ties
A program may correctly identify the winning combinations but overlook situations where both players select the same move.
The simplest solution is to check equality first:
if (user.equals(computer))
{
return "Tie";
}
Handling ties before the other outcomes keeps the conditional logic straightforward.
Incorrect Random Number Ranges
Another possible error involves generating the wrong range of random numbers.
For example:
Randomizer.nextInt(1, 2);
This produces only 1 or 2 in the CodeHS Java library.
If three moves are represented by the numbers 1, 2, and 3, the correct call is:
Randomizer.nextInt(1, 3);
Without the third possible value, the computer would never select one of the moves.
Creating a Loop That Never Ends
A loop such as:
while (true)
{
// Game instructions
}
will continue unless there is a reachable exit condition, an exception, or an external interruption.
For this game, the exit condition should detect when the player submits an empty input.
The break statement allows the program to terminate normally.
Not Checking Invalid Input
Without input validation, a player might enter an unexpected value such as "stone" or "r".
If the winner method assumes that every input is valid, it can produce a misleading result.
Checking the user’s choice before determining the winner prevents this issue.
For example:
if (!isValidChoice(user))
{
System.out.println("Invalid choice.");
continue;
}
This allows the program to request another move instead of treating invalid input as a legitimate choice.
Problems with ConsoleProgram or Randomizer
Some students copy their CodeHS Java code into another development environment and receive errors involving ConsoleProgram, readLine(), or Randomizer.
These classes and methods are associated with the CodeHS Java library rather than standard Java’s built-in API.
CodeHS explains that programs relying on its platform-specific libraries may need those libraries installed when used outside the CodeHS editor.
See the CodeHS guide to using code outside its editor for additional information.
How to Test Your CodeHS Rock Paper Scissors Program
Testing is essential because a program that compiles successfully can still produce incorrect results.
A useful testing strategy is to verify each important behavior separately.
Test the Game Rules
The getWinner() method can be tested without relying on random computer selections.
For example:
System.out.println(getWinner("rock", "scissors"));
System.out.println(getWinner("paper", "rock"));
System.out.println(getWinner("scissors", "paper"));
System.out.println(getWinner("rock", "rock"));
The expected output is:
User wins!
User wins!
User wins!
Tie
These tests confirm that the method correctly identifies the three user-winning combinations and a tie.
Additional tests should cover the three computer-winning combinations.
Temporary testing statements should be removed when they are no longer needed.
Check All Important Input Scenarios
| Test | Input | Expected Behavior |
|---|---|---|
| Valid choice | rock | Plays a round |
| Valid choice | paper | Plays a round |
| Valid choice | scissors | Plays a round |
| Uppercase input | ROCK | Accepted after normalization in the example |
| Extra whitespace | paper | Accepted after trimming in the example |
| Invalid input | stone | Displays an error and requests another choice |
| Empty input | Press Enter | Ends the game |
| Multiple rounds | Enter several valid moves | Continues playing |
Students should also verify that the program displays the correct message for each winning and losing combination.
An automated grading system may check more than whether the program runs. It may also check required method names, return values, output formatting, and other assignment-specific behavior.
For this reason, a logically correct implementation may still require adjustments to match the provided CodeHS instructions.
What Programming Concepts Does This Exercise Teach?
The Rock, Paper, Scissors assignment brings together several important Java concepts.
Conditional Statements
Conditional statements allow a program to make decisions based on whether an expression evaluates to true or false.
In this game, if and else statements determine whether a round ends in a win, loss, or tie.
These statements are fundamental to applications that must respond differently under different conditions.
Methods and Reusable Logic
A method is a named section of code that performs a particular task.
For example, the getWinner() method can evaluate different rounds without repeating the winner-determination logic throughout the program.
This demonstrates an important principle of software development: functionality should be organized into manageable, reusable components.
Loops and Repeated Execution
The while loop allows the player to complete multiple rounds during a single program execution.
Without a loop, the program would play one round and finish.
Loops are also used in menus, repeated calculations, data processing, and many other applications.
Random Number Generation
The computer needs a method of selecting a move without requiring another human player.
Random number generation provides that functionality.
With three equally likely outcomes, each computer move has a probability of one-third under the intended uniform random selection. This makes the computer’s basic strategy unpredictable rather than fixed.
Random selection is useful in simulations, games, randomized testing, and other programming tasks.
Working with Strings
A string represents text in Java.
The exercise demonstrates how strings can store user input, represent game moves, and return meaningful results.
Methods such as equals(), trim(), and toLowerCase() make text-based input easier to process accurately.
How Can Students Improve the Rock Paper Scissors Game?
After implementing the required functionality, students can explore additional features to strengthen their programming skills.
These improvements are optional learning extensions, not verified requirements of the standard exercise.
Add a Score Counter
A scoreboard can track the number of rounds won by the player and the computer.
For example:
int userScore = 0;
int computerScore = 0;
int ties = 0;
After each round, the program can update the appropriate variable.
It can then display a running scoreboard:
User Wins: 3
Computer Wins: 2
Ties: 1
This extension introduces persistent state within a program, meaning information is retained and updated across repeated actions.
Add a Best-of-Five Mode
Another extension is to create a match that ends when either player wins three rounds.
This requires a condition that checks the current score after every round.
Students can then display the overall match winner rather than evaluating only individual rounds.
Calculate Win Percentages
The program can also report how often the player wins.
For example, a player who wins 4 of 10 completed rounds has a win percentage of 40%.
The calculation is:
double winPercentage =
(double) userScore / totalRounds * 100;
The program should ensure that totalRounds is greater than zero before performing the calculation.
This introduces type casting and basic numerical analysis.
Create a Graphical Version
A more advanced project could replace typed input with interactive buttons.
The program could display images representing rock, paper, and scissors, along with a visual scoreboard.
However, graphical programming introduces additional concepts and may require a different program structure or library.
The console-based version remains the better starting point for learning the logic.
CodeHS 4.7.11 vs. 4.7.10: What Is the Difference?
Although these exercises are closely related, they emphasize different aspects of programming.
| Feature | Exercise 4.7.10 | Exercise 4.7.11 |
|---|---|---|
| Main focus | Determining the winner | Creating the complete game |
| Winner logic | Central task | Reused within gameplay |
| Interactive user input | Not the main focus | Required for the game |
| Random computer move | Not the main focus | Part of gameplay |
| Repeated rounds | Not the main focus | Part of the exercise |
| Primary learning outcome | Method and conditional logic | Combining methods, input, randomness, and loops |
CodeHS lists 4.7.10 as a practice activity and 4.7.11 as an exercise in the same lesson.
Students who understand the winner-determination method from 4.7.10 will generally find the larger game easier to construct.
Frequently Asked Questions
1. What is the answer to CodeHS 4.7.11 Rock Paper Scissors?
The exercise requires a Java program that allows a user to choose rock, paper, or scissors, generates a random computer choice, and determines the winner. It must also support repeated rounds until the user ends the game.
The complete example in this guide demonstrates one way to implement that functionality. Its compatibility with a particular CodeHS grader depends on the assignment’s exact requirements.
2. Is CodeHS 4.7.11 written in Java or Python?
The 4.7.11 Rock, Paper, Scissors! exercise identified in the official CodeHS Introduction to Java curriculum is a Java assignment. CodeHS also offers programming activities involving similar games in other languages, so students should check the title and course associated with their own exercise.
3. How do you generate a random choice in CodeHS Java?
You can use Randomizer.nextInt(1, 3) to generate an integer from 1 through 3, inclusive. Assign each number to rock, paper, or scissors.
The CodeHS Randomizer library provides this functionality without requiring students to implement their own random number generator.
4. Why does my CodeHS Rock Paper Scissors program keep running?
The most likely cause is a loop that does not correctly detect when the user wants to stop.
Check whether the program tests for an empty response and executes break when that condition is met.
Also verify that the exit condition can actually be reached during execution.
5. Why is my getWinner() method producing incorrect results?
Incorrect results usually come from missing conditions, reversed winning rules, or improper string comparisons.
First, verify ties. Then confirm that rock beats scissors, paper beats rock, and scissors beat paper.
Use equals() instead of == when comparing Java string values.
6. Can I run CodeHS Rock Paper Scissors outside the CodeHS website?
Yes, but code that uses the CodeHS-specific ConsoleProgram or Randomizer classes requires the appropriate library support.
Alternatively, the application can be adapted to standard Java using Scanner for input and java.util.Random for random selections.
The underlying game logic remains the same, although the surrounding code changes.
Final Takeaway
CodeHS 4.7.11 Rock Paper Scissors is a practical exercise for understanding how Java methods, conditional statements, random selection, and loops work together.
The most reliable approach is to build the game in separate parts: handle user input, generate the computer’s selection, determine the winner, and repeat the process until the user exits.
Students should focus on understanding each part of the program rather than simply copying a finished solution. That understanding is useful for completing more advanced Java assignments and building interactive applications.
Also Read: Miniondle: How to Play the Daily Minions Guessing Game
-
General News1 month agoBlooket Host: How to Host, Join, and Play Games
-
Celebrity3 weeks agoBarbara Joyce Rupard: Life, Family and Roy Clark’s Legacy
-
Celebrity Biography1 month agoCatherine Rusoff Ethnicity: Background, Heritage and Family
-
Celebrity Net Worth3 weeks agoAzim Premji And Nissan Makoto Net Worth Comparison (2026)
-
General News2 weeks agoPaul Mauro Wikipedia: Biography, NYPD Career & Fox News
-
General News1 month agoGimkit Host: Complete Guide to Hosting and Joining Games
-
Celebrity Biography2 weeks agoDani Beckstrom Age: Birthday, Biography and Career in 2026
-
Celebrity Net Worth2 weeks agoCal Henderson and Stewart Butterfield Net Worth Comparison (2026)
