Get the App
SLTechnology News&Howtos  ›  Development  › 

What's the use of Java Random?

Shulou Source: shulou.com Published: 2022-06-02 04:12:51 09月15日 Update

This article mainly introduces the use of Java Random, the article is very detailed, has a certain reference value, interested friends must read it!

The Random class is located under the java.util package, and instances of this class are used to generate random numbers.

Case 1:

Import java.util.Random

Import java.util.Scanner

Public class RandomDemo {

Public static void main (String [] args) {

/ / the system generates a random number between 1 and 100

Random r = new Random ()

/ / get random number

Int number = r.nextInt (100) + 1

/ / guess the data many times

While (true) {

/ / enter the data to be guessed by the keyboard

Scanner sc = new Scanner (System.in)

System.out.println ("Please enter the data you guessed (range 1100):")

Int guessnumber = sc.nextInt ()

/ / compare two data and use if statement to realize

If (guessnumber > number) {

System.out.println ("you guess the data is too big")

} else if (guessnumber < number) {

System.out.println ("your guess is small")

} else {

System.out.println ("Congratulations, you guessed right")

Break

}

}

}

}

Running result:

Please enter the data you guessed (range 1-100):

twelve

The number you guessed is small.

Case 2:

Import java.util.Random

Public class CallName {

Public static void main (String [] args) {

System.out.println ("students in the class:")

String [] arr = {"zhangsan", "lisi", "wangwu", "sjls", "qianqi"}

For (int I = 0; I < arr.length;i++) {

System.out.print ("student number" + (item1) + ":" + arr [I] + "")

}

System.out.println ()

/ / use random numbers for roll call

Random ran = new Random ()

Int index = ran.nextInt (arr.length)

System.out.println ("student number" + (index+1) + ":" + arr [index] + "")

}

}

Running result:

The students in the class are:

Student number 1: zhangsan student number 2: lisi student number 3: wangwu student number 4: sjls student number 5: qianqi

Student number 3: wangwu

Case 3:

Import java.util.*

Public class V {

Public static void main (String [] args) {

Int a [] = new int [100]

For (int iTuno Bandi)

Tags: Student number data random number case result run content classmate class article scope input right between two value interest example boy partner Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn Shulou Information Xiaomi Linux MariaDB