# Zufallszahlen erzeugen



## MiRaMC (15. Februar 2004)

Wie kann man eine Zufallszahlin einem bestimmten Zahlenbereich erzeugen, wobei einige Zahlen ausgelassen werden. 
Also z.B.: Ein Zahl zwischen  1 und 20, aber nicht 5, 10 & 15?


----------



## tomkruse (15. Februar 2004)

Hi!

Sieh Dir mal die Klasse Random an. Damit geht das ...

Cu - Tom.


----------



## Thomas Darimont (16. Februar 2004)

Hi!

Eigene Klasse RangeRandom:


```
import java.util.Random;

/*
 * Created on 16.02.2004
 *
 * To change the template for this generated file go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */

/**
 * @author Darimont
 *
 * To change the template for this generated type comment go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
public class RandomRange extends Random {

	private int fromRange;
	private int toRange;

	private int[] exceptVals;

	public RandomRange() {
		this(0, 100, null, 0l);
	}

	public RandomRange(int from, int to, int[] except, long seed) {
		super();
		this.fromRange = from;
		this.toRange = to;
		this.exceptVals = except;
		super.setSeed(seed);
	}

	public int nextInt() {

		int val = super.nextInt(toRange);
		if (exceptVals == null)
			return val;

		while (checkForExceptVals(val) != 0) {
			val = super.nextInt(toRange);
		}
		return val;
	}

	/**
	 * Returns 0 if no exceptVals were found
	 * Returns -1 if exceptVals were found
	 */
	private int checkForExceptVals(int val) {
		for (int i = 0; i < exceptVals.length; i++) {
			if (exceptVals[i] == val)
				return -1;
		}
		return 0;
	}
}
```

Angewendet:


```
/*
 * Created on 16.02.2004
 *
 * To change the template for this generated file go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */

/**
 * @author Darimont
 *
 * To change the template for this generated type comment go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
public class RandomTest {

	public static void main(String[] args) {
		
		/*
		 * Startwert 1,
		 * Endwert 11
		 * Ausnahmen 2,4,6,8
		 * Interner Startwert
		 */
		RandomRange rr =
			new RandomRange(1, 11, new int[] { 2,4,6,8 }, 0l);
		for (int i = 0; i < 100; i++) {
			System.out.println(rr.nextInt());
		}
	}
}
```

Gruß Tom


----------

