Learn Java Easy. Chapter 9. Creating a Distraction Device. With Loops, Conditionals and Scanner

Chapter 9. Creating a distraction device. With loops, conditionals and scanner

Chapter 9. Creating a distraction device. With loops, conditionals and scanner

I hadn’t realized it, but I’ve already been behind bars for almost a month and a half. It may not be a long time, but I’ve already forged a great friendship with Bud. I told him about my situation and he’s willing to help me. Today, finally, he’s going to tell me the plan that will allow me to get out of here. He hasn’t given me any clues, so I have no idea how we’re going to do it.

Bud is quite happy with my Java level. I’ve been a good student and I’m learning very quickly. The problem is that if I escape from prison, I can forget about continuing my progress. My future is very uncertain at the moment. I can only make daily plans; planning things from one week to another is a luxury.

My fate is uncertain. Just today, I received a message from one of the guards: I’ve been assigned a job in the laundry. At three o’clock in the afternoon I have to report there, and I don’t know what my task will be. Whatever it is, it’s sure to be better than being in the cell doing nothing.

I’ve been alone in the cell all day. It’s nice to have a little privacy from time to time. Solitude sometimes helps you clear your mind. Time has passed very quickly and, without realizing it, I’m already on my way to the laundry. I wonder how many people work there. I might be able to make new friends.

As soon as I arrived, I realized that my plan to socialize was completely ruined. Those who were waiting for me were actually Bud and Pedro. It was then that they told me they had a plan to escape from prison. They needed one more person and, thanks to my programming knowledge, I could join them.

There was a small problem. They wanted to escape, but I actually didn’t. I didn’t want to spend the rest of my life running away. I need to get out for a while to unmask Rich. Bud knew this, so he offered me a solution. The two of them would escape, but I, after two hours, would return to prison. It should be enough to get a confession from Rich, return to my cell and for no one to find out about my excursion.

It took me less than two minutes to decide. Of course, I accepted. I think these two have everything well studied, so it seems that the risk is minimal. What I didn’t know is that the plan was going to start the next day. Bud hadn’t been teaching me Java by chance. They needed a third person who knew how to program to carry out the plan.

The first part of the plan is simple. Well, at least my contribution. In the prison library there are several computers that can access the entire security system. From there, Pedro is going to access the prison alarm function and make it go off for a few minutes. Thanks to that distraction, Bud will be able to access the director’s office, where he will get something that will help us in the next step.

It’s important to access from one of the library computers, since if it’s done from Pedro’s or Bud’s computer, they would be discovered within minutes. Both laptops are very controlled and every action is recorded.

There’s a small problem, and that is that Pedro won’t have much time to hack the system. The truth is that there’s a lot to program and only a few minutes to do it without being discovered. That’s where I come in. I must create five Java programs, hidden on the library PC, that Pedro will later use to do his magic.

I have exactly one hour of time in the library. But normally the computers are in high demand, so I may only be able to use them for half an hour. It doesn’t matter, they’ve explained exactly what I have to do, so I have plenty of time.

Tomorrow is the big day. I’m a bit nervous, but tonight I’ll try to rest. It’s not easy to sleep under these circumstances, but I’ll try to think that if everything goes well, I’ll prove my innocence and finally be able to get out of here.

Program 1

The first thing will be to create a program that discovers the central system password. The password consists of 6 digits, of which we believe we know 5. Therefore, we simply have to check 10 combinations.

The problem is that if the data is checked too quickly, the system can detect it. So, after the ninth attempt, you have to wait at least 30 seconds. To do this, we will make the program stop after trying 9 attempts, and to check the last one we will have to type “continue” on the keyboard.

Here is the code I used. Review line by line and you’ll see how you understand its operation without problems:

Solution:

import java.util.Scanner;

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

        // Pass is the password we don't know. It's hidden in the program.
        // For now we generate a variable for it and give it value 0.
        // But in the real prison code lines it's a real password.
        int pass = 0;

        // We know all the numbers of the password except the last one.
        int incompletePass = 58987;

        // We declare the variable for the attempts to guess the password.
        int completePass;

        // We create a Scanner since we'll need to enter text.
        Scanner scan = new Scanner(System.in);

        // We create a variable to continue
        // In case of reaching the ninth attempt Pedro must wait 30 seconds
        // Then he must press "continue"
        String continueStr = "continue";

        // Our program will have 10 attempts.
        // So we create a "for" loop for it.
        for (int i = 0; i < 10; i++) {

            // This way we generate the last number that is added
            // to our incomplete password.
            completePass = incompletePass * 10 + i;

            // When our attempt matches the real password,
            // a text will be displayed.
            if (pass == completePass) {
                System.out.println("This is the password");
                break;
            }

            // We need to warn Pedro if the program has made 8 attempts
            // Then he decides if he wants to try the last one
            if (i == 9) {
                System.out.println("This is the ninth attempt, you must wait 30 seconds");
                System.out.println("Type continue to continue");
                String pause = scan.nextLine();

                if (!continueStr.equals(pause)) {
                    System.out.println("Error");
                    System.exit(0);
                }
            }
        }

        System.out.println("Password successfully obtained: " + pass);
    }
}

Program 2

With the password we can enter the central system; from there, we can access the alarm. This is located in a circuit where energy is generally saved and is turned off all the time. Therefore, first of all, we have to make sure that the electricity is working. After this condition is met, Pedro must mark the manual fire alarm option as true. This way, he will later be able to make it go off. Let's leave him the code well prepared.

Let's create a program that looks for the boolean variable alarmActivated and marks it as true. But only if the boolean variable electricityOn is activated. If not, the program will have to activate it.

Solution:

public class Main {
    public static void main(String[] args) {
        // Declaration of variables
        boolean electricityOn = false;
        boolean alarmActivated = false;

        // Check the status of electricityOn
        if (electricityOn) {
            // If electricityOn is activated, we activate the alarm
            alarmActivated = true;
            System.out.println("Electricity is activated. The alarm has been activated.");
        } else {
            // If electricityOn is not activated, we activate it and then activate the alarm
            electricityOn = true;
            alarmActivated = true;
            System.out.println("Electricity was not activated. Electricity and the alarm have been activated.");
        }

        // Show the final status of the variables
        System.out.println("Final status - Electricity: " + electricityOn
                + ", Alarm: " + alarmActivated);
    }
}

Program 3

The alarm cannot go off at any time. It must do so when all the prison guards are in their guard posts. This way, until they reach the central room to deactivate the alarm, at least 60 seconds will pass. That's the time we need for the distraction to last. In the hypothetical case that only one guard is in the central room, he could turn off the alarm in a few seconds and the plan would be ruined.

The prison system marks each guard post with a 1 if there is someone inside and with a 0 if it is empty. Therefore, we must create a program in which a 2D matrix is established that represents the 6 guard posts of the prison. Then, we create a boolean variable that is true if all the guard posts are occupied. If at least one is free, it will be false.

Solution:

public class Prison {

    public static void main(String[] args) {

        // Create a 2D matrix of 6 rows and 1 column to represent the 6 guard posts
        int[][] guardPosts = {
            {1}, // Guard Post 1
            {1}, // Guard Post 2
            {1}, // Guard Post 3
            {1}, // Guard Post 4
            {1}, // Guard Post 5
            {1}  // Guard Post 6
        };

        // Boolean variable that indicates if all guard posts are occupied
        boolean allOccupied = true;

        // Check the status of the guard posts
        for (int i = 0; i < guardPosts.length; i++) {
            if (guardPosts[i][0] == 0) {
                allOccupied = false;
                break;
            }
        }

        // Print the result
        if (allOccupied) {
            System.out.println("All guard posts are occupied.");
        } else {
            System.out.println("There are free guard posts.");
        }
    }
}

Program 4

In addition to the 60 seconds of sound distraction, we'll need the complex lights to turn off afterward. So the plan is that once the guards deactivate the alarm, there will be an instant blackout. Our job is to create a simple program that changes the status of a boolean variable called turnOffLights from false to true.

Solution:

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

        boolean turnOffLights = false; // Initial status of the turnOffLights variable
        System.out.println("Initial status of turnOffLights: " + turnOffLights);

        // Change the status of turnOffLights from false to true
        turnOffLights = true;
        System.out.println("New status of turnOffLights: " + turnOffLights);
    }
}

Program 5

Those are all the programs Pedro will need to provide a good distraction for Bud. But he also needs to cover his back. The alarm cannot sound while he is sitting in front of a computer. It would be very obvious that he is responsible. We must create a very simple program in which the number of seconds needed for the alarm to start sounding is entered by keyboard. This way, Pedro will be able to leave the library without anyone suspecting it was him. Depending on the situation, he himself will decide how many seconds he needs.

The only condition is that the entered number must be greater than 600. That equals 10 minutes, so Pedro will have enough time to reach his cell and for no one to suspect.

Solution:

import java.util.Scanner;

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

        Scanner scanner = new Scanner(System.in);

        // Ask the user to enter a number

        System.out.print("Enter a number greater than 600: ");
        int number = scanner.nextInt();

        // Verify if the number is greater than 600

        if (number > 600) {

            System.out.println("The number " + number + " is correct.");

        } else {

            System.out.println("The number is not correct. It must be greater than 600.");

        }

        // Close the scanner

        scanner.close();
    }
}

Did you like it? Don’t keep it to yourself — share it like juicy gossip! 😏