C# need to add random response with switch statement - c#

namespace _7._39
{
class Program
{
static void Main(string[] args)
{
string response1;
string response2;
string response3;
string response4;
Random resp = new Random();
bool correct = Question();// Create a value to call the question method
if (correct== true)// when the answer is true it return very good
{
Console.WriteLine("Very Good!");
}
else// when the answer is false it returns to try again
{
Console.WriteLine("No please try again");
}
}
public static bool Question()
{
Random rand = new Random();// we create a random number
int num = rand.Next(1, 9);// first random number between 1 and 9
int num1 = rand.Next(1, 9);// second random number between 1 and 9
int ans = num * num1;// the value of multiplication between 1 and 2
// asking what the two values are multiplied
Console.WriteLine("What is"+ num.ToString()+ "*" +num1.ToString());
// reads the users attempt
int attempt = int.Parse(Console.ReadLine());
if (attempt == ans)// when the attempt is equal to the answer
{
return true;// its returns true bool
}
else// if it is false it says no please try again
{
Console.WriteLine("No please try again");
return Question();// and creates a new question for the user
}
}
}
}
I need my correct== true and false to respond with a random response among 4 possible choices. I need to do this by doing a switch statement to issue each response. Also by using random to select which response comes up.
Very good!
Excellent!
Nice work!
Keep up the good work!
and 4 options for a false response as well
How can i implement this code into my current code?
response = resp.Next(1, 5);
switch (response)
{
case 1:
Console.WriteLine("Very Good!");
break;
case 2:
Console.WriteLine("Excellent!");
break;
case 3:
Console.WriteLine("Nice Work!");
break;
case 4:
Console.WriteLine("Keep up the good work!");
break;
default;
}

Try this:
var rnd = new Random();
Func<bool, string> getRespose = b =>
{
var choices = b
? new [] { "Very good!", "Excellent!", "Nice work!", "Keep up the good work!", }
: new [] { "Bad!", "V Bad!", "VV Bad!", "VVV Bad!", };
return choices[rnd.Next(0, choices.Length)];
};
No need for a switch statement.
Or if you want it as a switch:
var rnd = new Random();
var choices = (string[])null;
switch (correct)
{
case true:
choices = new []
{ "Very good!", "Excellent!", "Nice work!", "Keep up the good work!", };
break;
case false:
choices = new [] { "Bad!", "V Bad!", "VV Bad!", "VVV Bad!", };
break;
}
var response = choices[rnd.Next(0, choices.Length)];
Or, with a switch and a Func:
var rnd = new Random();
Func<bool, string> getRespose = b =>
{
var choices = (string[])null;
switch (b)
{
case true:
choices = new []
{ "Very good!", "Excellent!", "Nice work!", "Keep up the good work!", };
break;
case false:
choices = new []
{ "Bad!", "V Bad!", "VV Bad!", "VVV Bad!", };
break;
}
return choices[rnd.Next(0, choices.Length)];
};
var response = getRespose(correct);
Or as a "normal" function:
private Random rnd = new Random();
private string GetRespose(bool b)
{
var choices = (string[])null;
switch (b)
{
case true:
choices = new []
{ "Very good!", "Excellent!", "Nice work!", "Keep up the good work!", };
break;
case false:
choices = new []
{ "Bad!", "V Bad!", "VV Bad!", "VVV Bad!", };
break;
}
return choices[rnd.Next(0, choices.Length)];
}
Or as a "normal" function, but without the switch:
private Random rnd = new Random();
private string GetRespose(bool b)
{
var choices = b
? new [] { "Very good!", "Excellent!", "Nice work!", "Keep up the good work!", }
: new [] { "Bad!", "V Bad!", "VV Bad!", "VVV Bad!", };
return choices[rnd.Next(0, choices.Length)];
}

Related

More elegant if statement

I'm looking to compare a value against a list and then set another variable based on this comparison.
My list is
1 = Red
4 = Blue
13 = Green
I could have a series of if statements but with a large list this looks messy
if (Type == 1)
{
Name = "Red";
}
else if (Type == 4)
{
Name = "Blue";
}
else if (Type == 13)
{
Name = "Green";
}
What's an efficient and tidy way to achieve the same?
Make use of dictionary store your values, it will make clean code with less line of code and readable too
Dictionary<int, string> data = new Dictionary<int, string>
{
{ 1, "Red" },
{ 4, "Blue" },
{ 13, "Green" }
};
string test;
if (data.TryGetValue(1, out test)) // Returns true.
{
Console.WriteLine(test);
}
I think you need to use switch here:
switch (Type)
{
case 1:
Name = "Red";
break;
case 4:
Name = "Blue";
break;
case 13:
Name = "Green";
break;
}
Use a switch statement insted
switch (Type)
{
case 1:
Name = "Red";
break;
case 4:
Name = "Blue";
break;
case 13:
Name = "Green";
break;
}
class Program
{
public enum EnumDisplayStatus
{
Red = 1,
Blue = 2,
Yellow = 3,
Orange = 4
}
static void Main()
{
int value = 3;
EnumDisplayStatus enumDisplayStatus = (EnumDisplayStatus)value;
string color = enumDisplayStatus.ToString();
Console.Write(color);
}
}
Use enum and get string with this way that I showed.

How can I make loop instead of switch statement?

How can I write this shorter? For each case I have to write this and then It is too long because there are 48 numbers so I need 48 cases. Is there a way to make a loop?
switch (ballBounce.ToString())
{
case "1":
if (ballBounce == n0)
{
textBox1.Text = number.ToString();
}
break;
case "2":
if (ballBounce == n1)
{
textBox1.Text = number.ToString();
}
break;
case "3":
if (ballBounce == n2)
{
textBox1.Text = number.ToString();
}
break; ...
The loop is useless in this case.
You can use dictionary.
private Dictinoary<string, string> cases = new Dictionary<string, string> {
{"1", "one"},
{"2", "two"},
// ...
};
// in some method
string text;
if (cases.TryGetValue(ballBounce.ToString(), out text)){
this.textBox1.Text = text;
}
If you want something smarter than simple value, you can have functions in the dictionary.
private Dictinoary<string, Func<string>> cases = new Dictionary<string, Func<string>> {
{"1", () => "one"},
{"2", () =>
{
if (DateTime.Now.Seconds % 2 == 0) { return "A"; }
else { return "B"; }
}},
// ...
};
// in some method
Func<string> textProvider;
if (cases.TryGetValue(ballBounce.ToString(), out textProvider)){
this.textBox1.Text = textProvider();
}
Based on your ToString()'s, I'm assuming that ballBounce is an int.
if (ballBounce <= 48 && ballBounce > 0)
{
textBox1.Text = ballBounce.ToString();
}
why do you use if with case?
you don't need to check twice.
also if this is the code for every case
textBox1.Text = number.ToString();
then you don't need switch or if
jsut write textBox1.Text = number.ToString(); and you are good to go.
also if you have some cases ony you can do it that way:
switch (ballBounce.ToString())
{
case "1":
case "2":
case"3":
//....
textBox1.Text = number.ToString();
}

Replace 4 different characters

I'm trying to take the user input, E.G. ATCG and replace the letters with TAGC. These are DNA Complementary Bases. For example, if the user was to enter ATCGGGC it would output TAGCCCG. I've managed to replace 1 character, but I'm not sure how to get the others to replace.
namespace DNA_Replication_EASY
{
class Program
{
static string input1;
public static string InputBaseWithSpaces()
{
return string.Join(" ", input1.ToCharArray());
}
public static string OpposingBases()
{
string outputBases1 = input1.Replace("A", "T");
return outputBases1;
}
static void Main(string[] args)
{
Console.WriteLine("Please type out your DNA strand bases E.g. A T C G C A T G");
input1 = Console.ReadLine();
Console.WriteLine(InputBaseWithSpaces());
Console.WriteLine(OpposingBases());
Console.ReadLine();
}
}
}
Use Regex.Replace to replace string based on a dictionary (map):
Dictionary<string, string> complementary = new Dictionary<string,string>()
{
{ "A", "T" },
{ "T", "A" },
{ "C", "G" },
{ "G", "C" }
};
string input = "ATCG";
string result = Regex.Replace(input, "[ATCG]", match => complementary[match.Value]);
this replaces any of the "ATCG" character match with corresponding value from dictionary.
string MakeOpposite(string sourceString) {
var opposites = new Dictionary<char, char> {
{ 'A', 'T' },
{ 'T', 'A' },
{ 'G', 'C' },
{ 'C', 'G' }
};
var oppositeString = new string(sourceString.Select(x => opposites[x]));
return oppositeString;
}
Convert it to a char array and replace in place
string input = "ATCG";
//TAGC
char[] inputChar = input.ToCharArray();
for(int i=0;i< inputChar.Length; i++)
{
switch(inputChar[i])
{
case 'A':
inputChar[i]='T';
break;
case 'T':
inputChar[i]='A';
break;
case 'G':
inputChar[i]='C';
break;
case 'C':
inputChar[i]='G';
break;
}
}
var output =new string(inputChar);
I would use a foreach and switch statement over your Char Array to replace each letter.
foreach (char base in strand)
{
switch (base.ToString())
{
case "g":
//replace code
break;
case "c":
//replace code
break;
}
}
You should instead write a routine to go through character by character and do the replacement (don't use the string.replace method).
private string ConvertDNA(string original)
{
StringBuilder newone = new StringBuilder();
foreach(char c in original)
{
switch(c)
{
case 'A':
newone.Append('T');
break;
case 'T':
newone.Append('A');
break;
case 'C':
newone.Append('G');
break;
case 'G':
newone.Append('C');
break;
default:
newone.Append(c);
break;
}
}
return newone.ToString();
}
Note that if your original string is certain forms of Unicode, this could do funny things. You should use stringbuilder rather than the += syntax in the other answers because its more efficient.
One way to do it is by using a Switch statement
public static string OpposingBases()
{
string outputBases1;
foreach(var s in input1)
{
switch (s)
{
case "A":
outputBases1 +="T";
break;
case "T":
outputBases1 +="A";
break;
case "C":
outputBases1 +="G";
break;
case "G":
outputBases1 +="C";
break;
case " ":
outputBases1 +=" ";
break;
default:
break;
}
}
return outputBases1;
}
Simple solution, but you can do better:
code = code.Replace("A","x").Replace("C","y").Replace("T","A").Replace("G","C").Replace("x","T").Replace("y","G");
You could do this
public static string OpposingBases()
{
var baseDictionary = new Dictionary<char, char>()
{
{'A', 'T'},
{'T', 'A'},
{'C', 'G'},
{'G', 'C'}
};
return input1.Where(baseDictionary.ContainsKey).Aggregate("", (current, c) => current + baseDictionary[c]);
}

Making a program that ask the user 5 questions in random without duplicate the questions [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Randomize a List<T> in C#
I want to make a program that ask the user 5 questions in random without duplicate the questions, and if the question is right go through the next question if wrong stop until he gave the right answer, and this is the code which I had written, but there are still some problems, like there are duplicate and when the user enter the wrong answer it only stop for one time, and then the program closed!
now how can I prevent duplicate the same question, and if he enter wrong value don't proceed to the next question or the program closed?
static void Main()
{
next:
Random question = new Random();
int x = question.Next(5);
string[] array = new string[5];
array[0] = "-What is the capital of France";
array[1] = "-What is the capital of Spain";
array[2] = "-What is the captial of Russia";
array[3] = "-What is the capital of Ukraine";
array[4] = "-What is the capital of Egypt";
Console.WriteLine(array[x]);
string[] answer = new string[5];
answer[0] = "Paris";
answer[1] = "Madrid";
answer[2] = "Moscow";
answer[3] = "Kiev";
answer[4] = "Cairo";
string a = Console.ReadLine();
if (a == answer[x])
{
Console.WriteLine("It's True \n*Next Question is:");
goto next;
}
else
Console.WriteLine("It's False \n*Please Try Again.");
Console.ReadLine();
}
You can shuffle indexes of asked question with LINQ
Random random = new Random();
var indexes = Enumerable.Range(0,array.Length).OrderBy(i => random.Next());
foreach(var index in indexes)
{
Console.WriteLine(array[index]);
do
{
string a = Console.ReadLine();
if (a == answer[index]) {
Console.WriteLine("It's True\n");
break;
}
Console.WriteLine("It's False \n*Please Try Again.");
}
while(true);
}
Explanation:
Enumerable.Range(0,array.Length) will return range of integer values starting from zero: 0, 1, 2, 3, 4. Next those numbers will be sorted by random number (i.e. shuffled). It could result in any combination of those numbers, e.g. 3, 0, 1, 4, 2.
BTW it's good to go OOP way and put related data (question text and answer) and logic (defining if answer is correct) into one place:
public class Question
{
public string Text { get; set; }
public string Answer { get; set; }
public bool IsCorrect(string answer)
{
return String.Compare(answer, Answer, true) == 0;
}
}
With this question class all your code will be more readable:
var questions = new List<Question>()
{
new Question { Text = "What is the capital of France?", Answer = "Paris" },
new Question { Text = "What is the capital of Spain?", Answer = "Madrid" },
new Question { Text = "What is the capital of Russia?", Answer = "Moscow" },
new Question { Text = "What is the capital of Ukraine?", Answer = "Kiev" },
new Question { Text = "What is the capital of Egypt?", Answer = "Cairo" }
};
Random random = new Random();
// randomizing is very simple in this case
foreach (var question in questions.OrderBy(q => random.Next()))
{
Console.WriteLine(question.Text);
do
{
var answer = Console.ReadLine();
if (question.IsCorrect(answer))
{
Console.WriteLine("It's True");
break;
}
Console.WriteLine("It's False. Please try again.");
}
while (true);
}
Next step for you is implementing Survey class, which will hold question asking, reading answers and displaying summary.
Do not use goto unless it is absolutely necessary.
public class Program
{
private static List<KeyValuePair<string, string>> questions = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string,string>("-What is the capital of France", "Paris"),
new KeyValuePair<string,string>("-What is the capital of Spain", "Madrid"),
new KeyValuePair<string,string>("-What is the captial of Russia", "Moscow"),
new KeyValuePair<string,string>("-What is the capital of Ukraine", "Kiev"),
new KeyValuePair<string,string>("-What is the capital of Egypt", "Cairo"),
};
static void Main()
{
var questions = ShuffleQuestions();
foreach(var question in questions)
{
bool done = false;
while(!done)
{
Console.WriteLine(question.Key);
string a = Console.ReadLine();
if (a == question.Value)
{
Console.WriteLine("It's True \n*Next Question is:");
done = true;
}
else
Console.WriteLine("It's False \n*Please Try Again.");
}
}
Console.ReadLine();
}
private IEnumerable<KeyValuePair<string, string>> ShuffleQuestions()
{
var list = questions;
var random = new Random();
int items = list.Count;
while (items > 1) {
items--;
int nextItem = random.Next(items + 1);
var value = list[nextItem];
list[nextItem] = list[items];
list[items] = value;
}
return list;
}
}
You could create a shuffled array of integers that represent the order to ask the questions in:
// Create question order
var order = Enumerable.Range(0, array.Length).ToArray();
for (int i = order.Length - 1; i > 1; --i)
{
var randomIndex = rnd.Next(i);
var temp = order[randomIndex];
order[randomIndex] = order[i];
order[i] = temp;
}
// Ask the questions in shuffled order
foreach(int questionIndex in order)
{
Console.Write(array[questionIndex]);
bool answeredCorrectly = Console.ReadLine() == answer[questionIndex];
}

I want something like the switch statement (but different of course)

Is there a C# construct like the switch statement that allows control to fall through the next level? I have something like this:
public static IEnumerable<string> SeverityOrHigher(string severity)
{
var result = new List<string>();
switch (severity.ToUpper())
{
case "ALL":
result.Add("ALL");
case "DEBUG":
result.Add("DEBUG");
case "INFO":
result.Add("INFO");
case "WARN":
result.Add("WARN");
case "ERROR":
result.Add("ERROR");
case "FATAL":
result.Add("FATAL");
case "OFF":
result.Add("OFF");
default:
break;
}
return result;
}
...which clearly does not work in C#, (Control cannot fall through from one case label...) yet it seems to me like it should. I know it expects breaks in there, but that would not give me the data flow I'm looking for. What can be done to make this happen the way I'd like?
In your case you can emulate "falling case" with a little bit of LINQ:
public static IEnumerable<string> SeverityOrHigher(string severity)
{
var result = new List<string>()
{ "ALL", "DEBUG", "INFO", "WARN", "ERROR", "FATAL", "OFF" };
return result.SkipWhile(l => l != severity.ToUpper()).ToArray();
}
Along with gotos, etc, you could do with this an enum and a bit of linq:
public static IEnumerable<Severity> SeverityOrHigher(Severity severity)
{
var value = (int) severity;
return Enum.GetValues(typeof (Severity))
.Cast<int>()
.Where(i => i >= value)
.Select(i => (Severity) i);
}
public enum Severity
{
All = 0,
Trace = 1,
Debug = 2,
Information = 3,
Warning = 4,
Error = 5,
Fatal = 6
}
It is not the optimal solution but you could use the goto statement like this:
switch (severity.ToUpper())
{
case "ALL":
result.Add("ALL");
goto case "DEBUG";
case "DEBUG":
result.Add("DEBUG");
goto case "INFO";
case "INFO":
result.Add("INFO");
goto case "WARN";
case "WARN":
result.Add("WARN");
goto case "ERROR";
case "ERROR":
result.Add("ERROR");
goto case "FATAL";
case "FATAL":
result.Add("FATAL");
goto case "OFF";
case "OFF":
result.Add("OFF");
break;
default:
break;
}
Use goto:
switch (severity.ToUpper())
{
case "ALL":
result.Add("ALL");
goto case "DEBUG";
case "DEBUG":
result.Add("DEBUG");
goto case "INFO";
case "INFO":
result.Add("INFO");
goto case "WARN";
case "WARN":
result.Add("WARN");
goto case "ERROR";
case "ERROR":
result.Add("ERROR");
goto case "FATAL";
case "FATAL":
result.Add("FATAL");
goto case "OFF";
case "OFF":
result.Add("OFF");
break;
default:
break;
}
Microsoft (implicitly) recommends this use: http://msdn.microsoft.com/en-us/library/06tc147t(v=vs.71).aspx
#nemesv's Linq answer is way better solution but if you want to do it with switch you could do like this and will get same result.
public static IEnumerable<string> SeverityOrHigher(string severity)
{
var lastFound = -1;
var severityList = new List<string>() { "ALL", "DEBUG", "INFO", "WARN", "ERROR", "FATAL", "OFF" };
var results = new List<string>();
foreach (var t in severityList)
{
if (lastFound > -1)
{
for (var index = lastFound + 1; index < severityList.Count; index++)
{
results.Add(severityList[index]);
}
return results;
}
switch (severity.ToUpper())
{
case "ALL":
results.Add(severity);
lastFound = 0;
break;
case "DEBUG":
lastFound = 1;
results.Add(severity);
break;
case "INFO":
lastFound = 2;
results.Add(severity);
break;
case "WARN":
lastFound = 3;
results.Add(severity);
break;
case "ERROR":
lastFound = 4;
results.Add(severity);
break;
case "FATAL":
lastFound = 5;
results.Add(severity);
break;
case "OFF":
lastFound = 6;
results.Add(severity);
break;
}
}
return results;
}
Test:
var list = SeverityOrHigher("ALL");
foreach (var severity in list)
{
Console.WriteLine(severity);
}
Console.ReadKey();
Does not look very nice, but could do the job for you:
string s = severity.ToUpper();
result.add("OFF");
if (s == "OFF")
return result;
result.add("FATAL");
if (s == "FATAL")
return result;
result.add("ERROR");
if (s == "ERROR")
return result;
// ...
result.add("ALL");
return result;
I'd go with somehting like creating another list which represents all valid severities and checking if the input severity is one of them:
public static IEnumerable<string> SeverityOrHigher(string severity)
{
var result = new List<string>();
var severities = new List<string> { "ALL", "DEBUG", "INFO", "WARN", "ERROR", "FATAL", "OFF" };
severity = severity.ToUpper();
if (severities.Contain(severity))
result.Add(severity);
return result;
}

Categories