Scratch to Java (Part-2)

1 min read

Scratch to Java

In this post, we’ll explore how Scratch code can translate to Java using the Magic 8-Ball Project.

Follow along to get hands-on experience in both worlds.

Step-1. Plan your code.

Try out the Magic 8 Ball program here:

What algorithm is behind this? In pseudocode, write down your Magic 8 Ball algorithm.

Step-2. Code it in Scratch

Scratch Example – Try it out!

3. Code it in Java

Download and install a Java editor, or use the free Popfizz online editor. Try out the Java version here.

  1. Go to Sign up or log in.
  2. Go to ‘My Project’.
  3. Click the plus sign to create a project. Select Java.

4. Start coding by creating a Java file. Name it ‘’. Then import the Scanner library to get user input.

import java.util.Scanner;

5. Declare a class and the main method. The class name must match the file name. The main method is first executed when the file is run. This is equivalent to the ‘When flag clicked’ block in Scratch.

public class MagicEightBall {
    public static void main(String[] args) {

6. Then in the main method, get ready to grab the user input by creating the Scanner object.

Scanner input = new Scanner(;

7. Insert a while-loop so that the program asks the user to enter a question until the user decides to exit the program. Then ask a question.

    System.out.println("What would you like to know?");

8. Then using the Scanner object input, get user input. This is equivalent to ‘Ask and wait’ block in Scratch.

    String response = input.nextLine();

9. Then using random, produce a random number between 1-8, inclusive.

    int rand = (int)(Math.random()*3) + 1;

9. Using an if-condition, create a way for the user to exit the program.


10. Create 8 more if-conditions that will output various responses based on the random number rand.

if (rand == 1){
    System.out.println("Not sure.");
if (rand == 2){
    System.out.println("Most definitely.");
if (rand == 3){
    System.out.println("Ask me later.");

The program is complete! Now let’s see how it matches with the Scratch program.

Complete code:

Starting the program:

Getting user input:

Forever loop:

Generating a random number:

Creating an if-condition to terminate the program:

Creating if-conditions to output random responses:

Related Links:

Leave a Reply

Get updates from Popfizz Computer Science in your inbox.