SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,kenrick Mock
Chapter:
Flow Of Control
Exercise:
Programming Projects
Question:11 | ISBN:9780132830317 | Edition: 5

Question

You have three identical prizes to give away and a pool of 30 finalists. The finalists are assigned numbers from 1 to 30. Write a program to randomly select the numbers of three finalists to receive a prize. Make sure not to pick the same number twice. For example, picking finalists 3, 15, 29 would be valid but picking 3, 3, 31 would be invalid because finalist number 3 is listed twice and 31 is not a valid finalist number.


TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Program:

// ThreeFinalists.java
import java.util.Random;
public class ThreeFinalists
{
	public static void main(String[] args)
	{
		Random rand = new Random();
		int num, finalist1 = 0, finalist2 = 0, finalist3 = 0;
		
		do
		{
			num = 1 + rand.nextInt(30);
			
			if(finalist1 == 0)
			{
				finalist1 = num;
			}
			else if(finalist2 == 0 && finalist1 != num)
			{
				finalist2 = num;
			}
			else if(finalist3 == 0 && finalist1 != num &&  finalist2 != num)
			{
				finalist3 = num;
			}
		}while(finalist1 == 0 || finalist2 == 0 || finalist3 == 0);
		
		System.out.println("Finalist #1: " + finalist1);
		System.out.println("Finalist #2: " + finalist2);
		System.out.println("Finalist #3: " + finalist3);
	}
}

Output:

Finalist #1: 21
Finalist #2: 8
Finalist #3: 19

 

0 0

Discussions

Post the discussion to improve the above solution.