Learn Java Easy. Chapter 6. Helping Bud. Random Numbers

Chapter 6: Helping Bud and Using Random Numbers in Java

Chapter 6. Helping Bud. Random Numbers

I have news from my lawyer and it is not good at all. My computer was used to access a criminal website that provided services to hack the security systems of companies. But that’s not all, this software is currently being used to extort several multinational companies.

The police believe I devised the plan with some accomplice who is still at large. I imagine they think it is Chani. I hope they catch him so this whole matter can be cleared up. Meanwhile, defending myself against the accusations is very difficult. My computer was involved and few people believe it was used without my permission.

The truth is I am not very optimistic. I imagine Chani has fled far away. If they don’t catch him, I will spend many years here. Again, I think about how life changes in an instant. I have done absolutely nothing and now I must pay for a crime I have nothing to do with. The worst part is that I can do nothing. I can only wait and see what happens. My social circle has drastically shrunk; I used to fill the house with friends on weekends. Now, I practically only talk to Bud and once a day with the visitors I receive from outside. My family is very worried and I know they are trying to help me from outside. I don’t feel alone, but sometimes I miss having more company.

At least I have Bud; we spend almost all day talking. Most of the time, about nonsense, nothing serious. It’s better to keep a clear head and try to disconnect a bit. Sometimes he asks me about my situation and follows the progress, but the truth is that not even I know what is going on.

Bud is lucky; he can spend much of the day with the computer. He can even leave the cell many times to help the prison staff with various IT tasks. Maybe, if I learn, I can also lend a hand. It could be a good opportunity to learn things, entertain myself, and, at the same time, see if they can reduce my sentence.

Bud loves to teach and continuously asks me surprise questions. He told me that if I apply myself, he might give me a little job or at least let me help him. We have a deal. He will teach me how to work with random numbers in Java and then give me a small test. If I pass it, he will let me help him.

Working with Random Numbers

Importance of Random Numbers in Java

Random numbers are constantly used in all kinds of programs. They can serve us, among other things, to simulate random events in games and simulations, generate data for software testing, and optimize algorithms through random decisions.

Additionally, they are vital in computer security to create keys and in data analysis to model statistical distributions. In short, random numbers in Java are versatile tools that improve robustness, security, and performance of computer systems in various applications.

Generating Random Numbers with Math.random

First of all, you should know that there is not a single way to generate random numbers. I will show you what, in my opinion, is the simplest. In Java, random number generation can be done using the Math class and its static method random(). The number we get is greater than or equal to 0.0 and less than 1.0. This means it can generate numbers like 0.0, but never reaches 1.0 (i.e., 0.999999999… is the maximum possible value).

As you can see, we have some limitations, but nothing we can’t solve with a bit of imagination and creativity.

Now, let’s see how to use Math.random() in practice to generate random numbers in Java:

We generate a random number between 0.0 (inclusive) and 1.0 (exclusive)

double number = Math.random(); System.out.println("Generated random number: " + number);

We generate a random number between two values. Using decimals.

For this, we use the following structure:

double number = Math.random() * (max - min) + min;

For example, if we want to create a random number between 10.0 (Included) and 100.0 (Excluded), we do it as follows:

double number = Math.random() * (100 - 10) + 10; System.out.println("Random number between 10.0 and 100.0: " + number);

We generate a random number between two values without decimals.

int number = (int) (Math.random() * (max – min +1) + min);

There are two changes in this line of code. The first thing we see is the use of (int). Thanks to that, our syntax changes from referring to a decimal variable to an integer. Notice that the rest of the line is also inside parentheses. It starts just before Math.random() and ends at the end. This basically removes all decimals. For example, if our random number is 88.87, now it will be 88.

If we continue with the example and want numbers from 10 to 100, before we could get values from 10.00 up to 99.999999… Therefore, if we remove the decimals, what we have is a range between 10 and 99. The problem is that it does not include

100. That leads us to the next change, which is the +1. By adding that element, our problem is solved, since the range now extends up to 100.99999…, which when converted to an integer gives us 100. This way, we have the range of random numbers we needed, 10-100.

Rounding the number of decimals using the Math.round() method

In the second topic, I already explained two ways to round the number of decimals and thus avoid a long tail of numbers. As I promised you then, here I bring you another way to achieve it. In my opinion, the simplest, although I considered it important to add the other two in this book. As you have already seen in the title of this section, we are going to use the Math.round() method, the same one we have been using throughout the topic to generate random numbers. I explain it directly with examples.

Rounding to two decimals:

public class Main {

         public static void main(String[] args) { 

               double number = 3.14159;

               double result = Math.round(number * 100.0) / 100.0; 

               System.out.println("Number with two decimals: " + result); 

               // Output: 3.14
 
        }

}

Rounding to three decimals:

public class Main {

            public static void main(String[] args) { 

                  double num = Math.random() * 10;

                  double result = Math.round(num * 1000.0) / 1000.0; 

                  System.out.println("Random number rounded to three decimals: " + result);

          }

}

Summary of what was learned

Random numbers are essential in programming in general. They are used, among other things, to simulate random events in games and simulations, generate data for software testing, or optimize algorithms. Additionally, they are crucial in computer security, used to create cryptographic keys, and in data analysis to model statistical distributions. These uses improve the security and performance of computer systems.

In Java, there are several ways to generate random numbers, but we will focus on one in particular. We create them using the Math class and its random() method. This method produces numbers between 0.0 (inclusive) and 1.0 (exclusive). With that numeric range, we are a bit limited, but that is no problem since with ingenuity we can access other values.

To generate a random number between two decimal numbers, the formula Math.random() * (max – min) + min is used.

To obtain a random integer in a specific range, the result is converted to an integer and the range is adjusted by adding 1, thus ensuring the inclusion of the upper value in the range.

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