The small project TryRandom is included in the folder of this chapter. Its source code is cited as follows. Input the range for the integer givenInt, and then run the project to verify whether the...


The small project TryRandom is included in the folder of


this chapter. Its source code is cited as follows. Input the


range for the integer givenInt, and then run the project to


verify whether the returned random value is in the ranges.


/*


 2 * TryRandom.java - The main class of the project TryRandom.


 3 */


 4 package tryrandom;


 5


 6 import java.util.Random;


 7 import javax.swing.JOptionPane;


 8


 13 public class TryRandom {


 14


 15 private int givenInt;


 16 private Random random2;


 17 private int min;


 18 private int max;


 19


 20 public TryRandom() {


 21 min = Integer.parseInt(JOptionPane.showInputDialog(


 22 "Enter the lower bound integer min: (e.g. 5)"));


 23 max = Integer.parseInt(JOptionPane.showInputDialog(


 24 "Enter the upper bound integer max: (e.g. 88"));


 25 System.out.println("The range is " + "[" + min + "," + max + "]");


 26


 27 givenInt = (int) (Math.random() * (max-min+1)) + min;


 28 System.out.println("givenInt1 = " + givenInt);


 29


 30 random2 = new Random();


 31 givenInt = random2.nextInt(max-min+1) + min;


 32 System.out.println("givenInt2 = " + givenInt);


 33


 34 givenInt = Math.abs(random2.nextInt()) % (max-min+1) + min;


 35 System.out.println("givenInt3 = " + givenInt);


 36 }


 37


 38 /**


 39 * @param args the command line arguments


 40 */


 41 public static void main(String[] args) {


 42 new TryRandom();


 43 }


 44 }

Nov 19, 2021
SOLUTION.PDF

Get Answer To This Question

Related Questions & Answers