2.6 Roll a die

Roll a die

Unit 2: Variables, Decisions, and Input · Lesson 2.6 Randomness · code exercise, graded

getRandomNumber(6) gives 0 to 5, never 6. A die gives 1 to 6. The gap between those two sentences is the whole lesson.

What to write

  1. Return a number from 1 to 6, each equally likely.
  2. Use Greenfoot.getRandomNumber.

The random numbers here are seeded, so the same code gives the same rolls every time. That is deliberate: a test that could fail at random would fail correct code.

Your code

This one prints numbers rather than moving anything, so there is nothing to animate. Press Submit to check it.



What it is checked against

These are the examples you can see. There are also 2 hidden cases with different setups, so printing the answers below as text passes nothing.

Example 1: what we set up

Greenfoot.__seed(20260816L);
Harness h = new Harness();
for (int i = 0; i < 6; i++)
{
System.out.println(h.roll());
}

What it should print

6
5
1
6
2
1

Example 2: what we set up

Greenfoot.__seed(7L);
Harness h = new Harness();
for (int i = 0; i < 4; i++)
{
System.out.println(h.roll());
}

What it should print

3
6
4
6

Get in Touch

Whether you're a student, parent, or teacher — I'd love to hear from you.

Just want free AP CS resources?

Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.

Typically responds within 24 hours

Message Sent!

Thanks for reaching out. I'll get back to you within 24 hours.

🏫 Welcome, fellow educator!

I offer curriculum resources, practice materials, and study guides designed for AP CS teachers. Let me know what you're looking for — whether it's classroom materials, a guest speaker, or Teachers Pay Teachers resources.

Email

[email protected]

📚

Courses

AP CSA, CSP, & Cybersecurity

Response Time

Within 24 hours

Prefer email? Reach me directly at [email protected]