Question: C# Program Making Decisions with if Statements In this lab you will learn to use if statements to drive decision making. Well also introduce the
C# Program Making Decisions with if Statements
In this lab you will learn to use if statements to drive decision making. Well also introduce the basics of random number generation.
Your Program
Your program for this lab simulates a Magic 8-Ball. The Magic 8-Ball is a fortune telling toy in which the player asks any Yes/No question and the Magic 8-Ball randomly answers the question with one of 20possible answers. A description of the game, along with the twenty answers can be found on the Wikipedia page.
For this program, you only need to use the following 5 answers:
- It is certain
-Reply hazy, Try Again
-Dont count on it
-Signs point to yes
-My sources say no
Inside the Main, you should first welcome the user, and prompt them to ask a question. You may choose to use a string variable to store the users question, but unless we want to repeat the question back to them in the output later, we dont actually care what the users question is. We arent actually telling the future just generating a random response.
Instead of storing it in a string, then, we can instead ignore their response. If we use a call to Console. ReadLine(), but do not assign the results to a variable, the user will still be prompted to enter something, but it wont be stored.
After reading the users question, your program will then randomly generate a number between 1 and5. Well use this value to select a random response.
To generate a random number, there are two steps we must take. The first is to declare a variable to represent our random number generator. We can do that using the syntax seen below.
Random rnd = new Random();
With our random number generator declared, we can generate a random number by calling rnd.Next().This function will return a randomly generated value between 0 and the largest value that an int can store (a bit more than 2.1 billion). To restrict this number to something between 1 and 5, we will first calculate the modulus of the value divided by 5 remember that modding by 5 will always return a value between 0 and 4. We can then add 1 to that result to get something from 1 to 5.
Storing the result in a variable, it might look something like
int roll = rnd.Next() % 5 + 1;
Once you have the randomly generated value, you should use an if...else if structure to choose which of the five messages to display, with one belonging to each possible value, 1 5.
Challenge (+15 Extra Credit)
Complete the lab a second time, replacing the if...else if structure with a switch statement to determine the appropriate response. Submit both versions of the lab as separate .cs files.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
