/* RandomExerciseMethod.java by Craig Persiko
Example program from CS 111A:
Generate random integers
in the range specified by user, showing them
on the screen, and stopping when the same number
is generated twice in a row. At the end, output
the largest number that was generated.
Uses a void method to do this
*/
import java.util.Scanner;
public class RandomExerciseMethod
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int smallest, largest;
System.out.println("Please enter the range of random numbers to generate:");
System.out.println("Enter the smallest number and largest number, separated by space:");
smallest = scan.nextInt();
largest = scan.nextInt();
randomness(smallest, largest);
}
/* Generate random integers in the range specified by parameters, showing them
on the screen, and stopping when the same number
is generated twice in a row. At the end, output
the largest number that was generated.
*/
public static void randomness(int smallest, int largest)
{
int rand=smallest-1, lastRand, max=smallest;
do
{
lastRand = rand;
rand = smallest + (int)( (largest-smallest+1) * Math.random());
System.out.print(rand + " ");
if (rand > max)
max = rand;
}while(rand != lastRand);
System.out.println("\nThe largest number was " + max);
}
}
/* Sample Output:
-bash-3.2$ java RandomExerciseMethod
Please enter the range of random numbers to generate:
Enter the smallest number and largest number, separated by space:
2 20
19 20 8 18 10 8 6 7 4 12 5 14 2 18 20 15 11 10 11 17 9 14 9 13 8 10 16 5 18 10 19 10 6 2 13 15 3 3
The largest number was 20
-bash-3.2$ java RandomExerciseMethod
Please enter the range of random numbers to generate:
Enter the smallest number and largest number, separated by space:
9 12
12 10 9 11 9 12 10 11 10 11 11
The largest number was 12
-bash-3.2$
*/
syntax highlighted by Code2HTML, v. 0.9