English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Per generare numeri casuali in Java, usa.
import java.util.Random;
Ora, usa la classe Random e crea un oggetto.
Random num = new Random();
Ora, usa questo nel ciclo.nextInt()
Il metodo, poiché viene utilizzato per ottenere il successivo valore intero casuale. Puoi anche impostare un intervallo, ad esempio da 0 a 20, scrivendo.
nextInt(20);
Vediamo un esempio completo, dove l'intervallo è da 1 a 10.
import java.util.Random; public class Demo { public static void main(String args[]) { Random num = new Random(); int res; for (int i = 1; i <= 5; i++) { res = 1 + num.nextInt(10); System.out.printf("%d", res); } } }
Risultato di output
4 5 9 6 9