Números aleatóris

Java

NetBeans

Lógica de programação

09/05/2018

Bom dia, gostaria de saber como gerar números aleatórios entre -10 e 10?
Fiz esse código porém ele só exibe valores entre 0 e 10!

Random gerador = new Random();

Integer valor = gerador.nextInt(10);
System.out.println(valor);
Lucas Sandes

Lucas Sandes

Curtidas 0

Melhor post

Angelo Santos

Angelo Santos

09/05/2018

Olá Lucas!

Tenta fazer dessa maneira:
public static void main(String[] args) {
		int max = 10;
		int min = -10;
		Random r = new Random();
		Integer v = r.nextInt(max + 1 - min) - 10;
		System.out.println(v);
	}


Espero ter ajudado. Bons estudos.
GOSTEI 3

Mais Respostas

Diego Medeiros

Diego Medeiros

09/05/2018


Uma forma bem legal tb é usando as mudanças do Java 8.

Random r = new Random();
int asInt = r.ints(-10, (10 + 1)).findFirst().getAsInt();


Vlww!
GOSTEI 0
POSTAR