The problem Write a method that returns a random integer between 1 and 54, excluding the numbers passed in the argument. The method header is specified as follows: public static int getRandom(int... numbers)
Breaking it down static final int NUMBERS_TO_REQUEST = 10 ;
public static void main ( String [] args ) {
int [] numbersToExclude = new int [ NUMBERS_TO_REQUEST ];
Scanner input = new Scanner ( System . in );
System . out . print ( "Enter ten numbers to exclude from random (1-54): " );
for ( int i = 0 ; i < numbersToExclude . length ; i ++) {
numbersToExclude [ i ] = input . nextInt ();
}
input . close ();
System . out . println ( "Number generated: " + getRandom ( numbersToExclude ));
}
public static int getRandom ( int ... numbersToExclude ) {
int random = getRandomNumber ();
for ( int i = 0 ; i < numbersToExclude . length ; i ++) {
if ( random == numbersToExclude [ i ]) {
random = getRandomNumber ();
i = - 1 ;
}
}
return random ;
}
private static int getRandomNumber () {
int random = ( int ) ( Math . random () * 54 + 1 );
return random ;
}
Output Enter ten numbers to exclude from random (1-54): 1
2
3
4
5
6
7
8
9
10
Number generated: 29
Random number chooser posted by Justin Musgrove on 24 April 2016
Tagged: java, java-exercises-beginner, intro-to-java-10th-edition, and ch7
Share on: Facebook Google+