วิธี Math.random() ใน Java คืออะไร?
0.0 ≤ random < 1.0
โปรดทราบว่าตัวเลขสุ่มมากกว่าหรือเท่ากับ 0.0และน้อยกว่า 1.0
จะใช้ Math.random() ใน Java ได้อย่างไร?
การใช้ เมธอด Math.random()นั้นค่อนข้างง่ายแม้สำหรับผู้เริ่มต้นตัวอย่างที่ 1
ลองดูตัวอย่างพื้นฐานเพื่อความเข้าใจที่ชัดเจนpublic class RandomTest {
public static void main(String[] args) {
double random1 = Math.random();
double random2 = Math.random();
System.out.println("First Random Number: " + random1);
System.out.println("Second Random Number: " + random2);
}
}
เอาท์พุต
หมายเลขสุ่มตัวแรก: 0.5486939400685561 หมายเลขสุ่มที่สอง: 0.23550115674999972
ใช้วิธีสุ่ม () ภายในช่วง
การเรียก เมธอด Math.random()ดูค่อนข้างอธิบายได้ในตัว อย่างไรก็ตาม ความต้องการตัวเลขสุ่มของเราไม่ได้อยู่ในช่วง 0 และ 1 เสมอไป สำหรับปัญหาในชีวิตจริง เราสามารถดำเนินการภายในช่วงอื่นๆ ที่ระบุได้เช่นกัน ลองดูตัวอย่างการใช้ เมธอด Math.random()สำหรับช่วงที่กำหนด เช่น 1 ถึง 50ตัวอย่างที่ 2
public class RandomNumberInRange {
public static int getRandom(int min, int max) {
int range = (max - min) + 1;
int random = (int) ((range * Math.random()) + min);
return random;
}
public static void main(String[] args) {
// Let's play Ludo with 4 Players
int dieRoll = getRandom(1, 6);
System.out.println("Red's Turn: " + dieRoll);
dieRoll = getRandom(1, 6);
System.out.println("Blue's Turn: " + dieRoll);
dieRoll = getRandom(1, 6);
System.out.println("Green's Turn: " + dieRoll);
dieRoll = getRandom(1, 6);
System.out.println("Yellow's Turn: " + dieRoll);
}
}
เอาท์พุต
เทิร์นของสีแดง: 3 เทิร์นของสีน้ำเงิน: 2 เทิร์นของสีเขียว: 6 เทิร์นของสีเหลือง: 4
GO TO FULL VERSION