מספרים אקראיים נמצאים בשימוש נרחב בתכנות עבור סימולציות של אבטחת משחקים וכו'. ישנן מספר דרכים ליצור מספרים אקראיים באמצעות שיטות מובנות ומחלקות ב-Java. הגישות הנפוצות ביותר מפורטות להלן:
- java.util.מחלקה אקראית
- שיטת Math.random() (מחזירה ערכים כפולים)
- מחלקה ThreadLocalRandom (הוצגה ב-Java 7)
הבה נחקור כל אחת מהגישות הללו אחת אחת בפירוט
1. שימוש ב-java.util.Random
בעזרת מחלקה זו נוכל ליצור מספרים אקראיים מסוגים שונים (int double long boolean וכו').
שיטות מפתח:
- nextInt(): שיטה זו יוצרת מספר שלם אקראי (טווח מלא כולל שליליים)
- nextInt(int bound): שיטה זו יוצרת מספר שלם אקראי בין 0 (כולל) לבין מאוגד (בלעדי)
- nextDouble(): שיטה זו יוצרת כפל אקראי בין 0.0 (כולל) ל-1.0 (בלעדי)
- nextBoolean(): אקראי נכון או לא נכון
דוּגמָה :
Java// Generating random number using java.util.Random; import java.util.Random; public class Geeks{ public static void main(String[] args) { // Creating the instance of Random class Random r= new Random(); // Generate random integers in range 0 to 999 int r1 = r.nextInt(1000); int r2 = r.nextInt(1000); // Printing random integers System.out.println('Random Integers: ' + r1); System.out.println('Random Integers: ' + r2); // Generate random doubles double rd1 = r.nextDouble(); double rd2 = r.nextDouble(); // Printing random doubles System.out.println('Random Doubles: ' + rd1); System.out.println('Random Doubles: ' + rd2); } }
תְפוּקָה
Random Integers: 39 Random Integers: 190 Random Doubles: 0.4200728082969115 Random Doubles: 0.9327571841228275
הפקת מספרים בטווח מסוים
הנוסחה ליצירת מספר אקראי עם טווח ספציפי מפורטת להלן:
Random rand = new Random();
int randomNum = rand.nextInt(max - min + 1) + min;
פֶּתֶק: min ומקסימום הם הגבול התחתון והגבוה יותר של המספר שלנו.
דוּגמָה:
Java// Generating random number in a specific range import java.io.*; import java.util.*; class Geeks { public static void main (String[] args) { Random r = new Random(); int max=100min=50; System.out.println('Generated numbers are within '+ min +' to '+ max); System.out.println(r.nextInt(max - min + 1) + min); System.out.println(r.nextInt(max - min + 1) + min); System.out.println(r.nextInt(max - min + 1) + min); } }
תְפוּקָה
Generated numbers are within 50 to 100 55 51 51
2. שימוש ב- Math.random()
ה שיעור מתמטיקה מכיל שיטות שונות לביצוע פעולות מספריות שונות כגון חישוב לוגריתמי האקספונציה וכו'. אחת מהשיטות הללו היא אַקרַאִי() שיטה זו מחזירה ערך כפול עם סימן חיובי גדול או שווה ל-0.0 וקטן מ-1.0. הערכים המוחזרים נבחרים בצורה פסאודו אקראית. שיטה זו יכולה ליצור רק מספרים אקראיים מסוג Doubles.
דוּגמָה:
מערך בתים של java למחרוזתJava
// Java program to demonstrate working of // Math.random() to generate random numbers import java.util.*; public class Geeks { public static void main(String args[]) { // Generating random doubles System.out.println('Random doubles: ' + Math.random()); System.out.println('Random doubles: ' + Math.random()); } }
תְפוּקָה
Random doubles: 0.38601320746656065 Random doubles: 0.9209882942481417
הפקת מספרים בטווח מסוים
הנה הנוסחה ליצירת מספר אקראי עם טווח ספציפי שבו המינימום והמקסימום הם הגבול התחתון והגבוה של המספר שלנו:
int randomNum = min + (int)(Math.random() * ((max - min) + 1));
דוּגמָה:
Java// Demonstrating how to generate random // number within a specific range import java.io.*; import java.util.*; class Geeks { public static void main (String[] args) { int max=100min=50; System.out.println('Generated numbers are within '+min+' to '+max); System.out.println(min + (int)(Math.random() * ((max - min) + 1))); System.out.println(min + (int)(Math.random() * ((max - min) + 1))); System.out.println(min + (int)(Math.random() * ((max - min) + 1))); } }
תְפוּקָה
Generated numbers are within 50 to 100 82 68 77
3. שימוש ב-ThreadLocalRandom
זוהי הדרך המומלצת בסביבות מרובות פתילים מכיוון שהיא מפחיתה מחלוקות.
שיטות מפתח:
- current().nextInt(): מספר שלם אקראי (טווח מלא)
- current().nextInt(min max + 1): מספר שלם אקראי בטווח (הוספתי את הדוגמה המוגבלת הזו)
- current().nextDouble(): כפול אקראי (0.0 עד 1.0)
- current().nextBoolean(): אקראי נכון או לא נכון
דוּגמָה:
Java// Demonstrates how to generate random integers // doubles and booleans using ThreadLocalRandom import java.util.concurrent.ThreadLocalRandom; public class Geeks { public static void main(String[] args) { // Generate random integers in range 0 to 999 // Random number between 0 and 999 int r1 = ThreadLocalRandom.current().nextInt(1000); // Random number between 0 and 999 int r2 = ThreadLocalRandom.current().nextInt(1000); // Print random integers System.out.println('Random Integers: ' + r1); System.out.println('Random Integers: ' + r2); // Generate Random doubles between 0.0 (inclusive) // and 1.0 (exclusive) double rd1 = ThreadLocalRandom.current().nextDouble(); double rd2 = ThreadLocalRandom.current().nextDouble(); // Print random doubles System.out.println('Random Doubles: ' + rd1); System.out.println('Random Doubles: ' + rd2); // Generate random booleans boolean rb1 = ThreadLocalRandom.current().nextBoolean(); boolean rb2 = ThreadLocalRandom.current().nextBoolean(); // Print random Booleans System.out.println('Random Booleans: ' + rb1); System.out.println('Random Booleans: ' + rb2); } }
תְפוּקָה
Random Integers: 812 Random Integers: 461 Random Doubles: 0.7420865203902993 Random Doubles: 0.9580683365617423 Random Booleans: false Random Booleans: false