Learn Java Easy. Chapter 6 Exercises

🎲 Random Number Exercises in Java | Solved Topic 6

Topic 6 Exercises

Exercise 1. Create a program that calculates the roll of twenty dice and the sum of the results.

Solution:

public class Main {

        public static void main(String[] args) { 

               int sum =0;

               //First we will create a loop for the 20 dice.

               //This way we won't have to copy and paste the same line 20 times. 

                for (int i=0; i<20;i++) {

                       //We use Math.random to generate random numbers.

                       //In this case we want the maximum to be six. That's why the multiplication.

                       //When we multiply by 6 we get numbers between 0 and 5.99. So we add 1.

                      //Now we have numbers between 1 and 6.99 but we must transform them into integers.

                       //This is done by converting the entire expression to an integer with (int). As shown below.

                        int a =(int)(Math.random()*6 + 1); sum = sum+a;

                 }

           System.out.println("The sum of the 20 dice is " + sum);
     
      }

}

Exercise 2. Java program that randomly displays 100 cards from a Spanish deck.

Solution:

public class Main {

     public static void main(String[] args) {

          String suit = ""; String figures = "";

          //We create a for loop to display 100 cards 

          for (int i = 0; i <= 100; i++) {

              //We create a random number from 1 to 4 to generate the suits. 

                int a = (int) (Math.random() * 4 + 1);
 
              //Depending on the value that comes out we assign a suit

               if (a == 1) {

                      suit = " golds ";

               }

               if (a == 2) {

                        suit = " swords ";

                 }

                 if (a == 3) {

                         suit = " cups ";

                 }

                  if (a == 4) {

                          suit = " clubs ";

                }


                //Now we create random numbers between 1 and 10.

                //From 1 to 7 will correspond to normal cards

                // 8 to jack, 9 to horse and 10 to king.

                int b = (int) (Math.random() * 10 + 1);

                //We give value to the figures variable as follows. 

                if (b==8) {

                     figures= "Jack";

                 }

                 if (b==9) {

                     figures= "Horse";

                }

                if (b==10) { 

                     figures= "King";

                 }

                //We display the results on the screen using conditionals. 

                 if (b==1) {

                        System.out.println("Ace of" + suit);

                 }

                   if (b>=2&&b<=7) { 

                        System.out.println(b + " of" + suit);

                  }

                  if (b>=8&&b<=10) { 

                        System.out.println(figures + " of" + suit);

                   }

            }

     }

}

Exercise 3. Java program that displays 20 random numbers between 0 and 100 on the same line.

Solution:

public class Main {

       public static void main(String[] args) { 

              for (int i=0;i<=20;i++){

               int a = (int)(Math.random()*100); 

               System.out.print(" " + a );

               }

       }

}

💡Understanding the Range: To generate a random number between two specific values, use the formula Math.random() * (max – min) + min. Make sure you understand that Math.random() generates a number between 0.0 and 1.0, so multiplying by (max – min) and then adding min correctly adjusts the range.

Exercise 4. Java program that displays 10 random numbers between 100 and 199 and then shows which was the largest and smallest.

Solution:

public class Main {

       public static void main(String[] args) {

            //We create the variables you see below.

            //The smallest number we can find is 0.

            //The largest number is 199.

            // The idea is that when a larger or smaller number comes out it replaces the ones we have.

            int largest = 0; int smallest= 199;

             for (int i=0;i<=10;i++){

                   int a = (int)(Math.random()*99+100);

                   //If the number that came out is greater than the current largest

                   //It becomes the new largest

                  if (a>largest) { 

                       largest = a;

                  }

                  //If the number that came out is smaller than the current smallest

                 //It becomes the new smallest


                if (a<smallest) { 

                        smallest = a;
         
                }

           }

           System.out.println("The largest number is: " + largest); 
           System.out.println("The smallest number is: " + smallest);

    }

}

Exercise 5. Create a program that draws numbers at random until 24 comes out. Then, it will count all the numbers that came out.

Solution:

public class Main {

         public static void main(String[] args) {

               int a = 0; 
               int sum=0;

           while (a!=24) { 

                a=(int)(Math.random()*100); sum++;

            }

           System.out.println("The total sum of numbers is: " + sum);

           }
}

Exercise 6. Create a program that randomly generates 20 grades and classifies them as sufficient, pass, notable and outstanding.

Solution:

public class Main {

       public static void main(String[] args) {

            String grade = "";

            for (int i=0;i<=20;i++) {

                 double a =(Math.random() * 10);

                 String result = String.format("%.2f", a);

                 if (a<5) {

                     grade = "Fail";

                 }

                if (a>=5&&a<7) { 

                       grade = "Sufficient";

                 }

                if (a>=7&&a<9) { 

                        grade = "Notable";

                 }

                 if (a>=9) {

                         grade = "Outstanding";

                  }

                  System.out.println(result + "----- > " + grade);

           }

     }

}

Exercise 7. Create a program that shows the roll of two dice until the same result comes up on both.

Solution:

public class Main {

       public static void main(String[] args) {

              int a =0;

              int b =1;

               while (a!=b) {

                      a =(int)(Math.random() * 6+1);

                      b =(int)(Math.random() * 6+1);

                       System.out.println("The dice roll is " + a + " " + b);

                 }

          }

}

💡Using Integers: To obtain integers in a specific range, convert it to an integer with (int). Additionally, adjust the range by adding 1 to the formula: (int)(Math.random() * (max – min + 1) + min). This includes both the minimum and maximum values in the range of possible results.

Exercise 8. Java program in which we have five attempts to guess a randomly created number.

Solution:

import java.util.Scanner; public class Main {

        public static void main(String[] args) {

              Scanner exercise = new Scanner(System.in); int attempts = 5;

              //We create a four-digit password. Between 1000 and 9999. 

              int password = (int)(Math.random()*9000+1000); 

              System.out.println("The password is " + password);

               while (attempts >0) { attempts--;

                     System.out.println("Enter a password "); 
                     int test = exercise.nextInt();

                     if (test==password) { 

                         System.out.println("You guessed it"); 
                         break;

                      }

                      if (attempts ==0) {

                          System.out.println("No more attempts");

                      }

               }

       }

}

Exercise 9. We create a program that simulates a lottery of 9 matches. Three columns will be shown where 1, X or 2 will be marked.

Solution:

public class Main {

       public static void main(String[] args) {

              System.out.println("The lottery result is as follows:"); 

              System.out.println(" ");
        
              for (int i =1;i<=9;i++) {

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

                                if (result==1) {

                                       System.out.println("Match " + i + " = " + " 1 |        |");

                                }

                                 if (result==2) {

                                       System.out.println("Match " + i + " = " + "        |  X  |");

                                 }

                                 if (result==3) {

                                       System.out.println("Match " + i + " = " + "        |  X  |  2");

                                 }

                     }

          }

}

💡Avoiding Undesired Values: If you need to exclude certain values from the range, use conditionals to regenerate the random number if you get an undesired value. For example, if you generate a random number and need to exclude 100, you can use a while loop to repeat the generation until you get a valid value.

Exercise 10. Java random number exercise, but in this case using a char variable. Create a program that shows the following symbols five times randomly: &^%$.*.

Solution:

public class Main {

      public static void main(String[] args) {

             char a= ' ';

             for (int i=1;i<=5;i++) {

                    int b = (int)(Math.random()*5+1); 

                     if (b==1) {

                             a = '&';

                     }

                     if (b==2) {

                              a = '*';

                      }

                     if (b==3) {

                              a = '^';

                       }

                      if (b==4) {

                              a = '%';

                       }

                       if (b==5) {

                             a = '$';

                       }

               System.out.println(a);

               }

}

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