I need help with a homework I have in school. These are the requirements from my teacher.
Program requirements:
Accept user input of a question.
Output a result based upon a real "magic 8-ball" (do not add any of your own)
use a switch statement
Create a Method with the following signature:
public static string responses ()
All user input and output should be done in your main method.
This is my code and I have a problem with returning the value and Visual Studio highlights the command break and reports an CS0162 Unreachable code detected.
using System;
public class Magic8Ball
{
public static void Main(string[] args)
{
Console.WriteLine("Ask you question to the Magic 8 Ball: ");
Console.ReadLine();
string response;
response = responses(response);
Console.WriteLine(response);
}
public static string responses(string response)
{
string affirmativeResponse1 = "It is certain.";
string affirmativeResponse2 = "It is decidedly so.";
string affirmativeResponse3 = "Without a doubt.";
string affirmativeResponse4 = "Yes definitely.";
string affirmativeResponse5 = "You may rely on it.";
string affirmativeResponse6 = "As I see it, yes.";
string affirmativeResponse7 = "Most likely.";
string affirmativeResponse8 = "Outlook good.";
string affirmativeResponse9 = "Yes.";
string affirmativeResponse10 = "Signs point to yes.";
string nonCommittalResponse1 = "Reply hazy, try again.";
string nonCommittalResponse2 = "Ask again later.";
string nonCommittalResponse3 = "Better not tell you now.";
string nonCommittalResponse4 = "Cannot predict now.";
string nonCommittalResponse5 = "Concentrate and ask again.";
string negativeResponse1 = "Don't count on it.";
string negativeResponse2 = "My reply is no.";
string negativeResponse3 = "My sources say no.";
string negativeResponse4 = "Outlook not so good.";
string negativeResponse5 = "Very doubtful.";
int numberOfResponse;
Random var = new Random();
numberOfResponse = var.Next(20);
switch (numberOfResponse)
{
case 0:
response = affirmativeResponse1;
return response;
break;
case 1:
response = affirmativeResponse2;
return response;
break;
case 2:
response = affirmativeResponse3;
return response;
break;
case 3:
response = affirmativeResponse4;
return response;
break;
case 4:
response = affirmativeResponse5;
return response;
break;
case 5:
response = affirmativeResponse6;
return response;
break;
case 6:
response = affirmativeResponse7;
return response;
break;
case 7:
response = affirmativeResponse8;
return response;
break;
case 8:
response = affirmativeResponse9;
return response;
break;
case 9:
response = affirmativeResponse10;
return response;
break;
case 10:
response = nonCommittalResponse1;
return response;
break;
case 11:
response = nonCommittalResponse2;
return response;
break;
case 12:
response = nonCommittalResponse3;
return response;
break;
case 13:
response = nonCommittalResponse4;
return response;
break;
case 14:
response = nonCommittalResponse5;
return response;
break;
case 15:
response = negativeResponse1;
return response;
break;
case 16:
response = negativeResponse2;
return response;
break;
case 17:
response = negativeResponse3;
return response;
break;
case 18:
response = negativeResponse4;
return response;
break;
case 19:
response = negativeResponse5;
return response;
break;
}
}
}
the "return" keyword pretty much ends the method so you don't really need to add the "break;" in this instance. Also you need to a default condition when using switch statements and lastly your string response needs to be set to the console.readline.
{
public static void Main(string[] args)
{
Console.WriteLine("Ask you question to the Magic 8 Ball: ");
string response = Console.ReadLine();
response = Responses(response);
Console.WriteLine(response);
}
public static string Responses(string response)
{
string affirmativeResponse1 = "It is certain.";
string affirmativeResponse2 = "It is decidedly so.";
string affirmativeResponse3 = "Without a doubt.";
string affirmativeResponse4 = "Yes definitely.";
string affirmativeResponse5 = "You may rely on it.";
string affirmativeResponse6 = "As I see it, yes.";
string affirmativeResponse7 = "Most likely.";
string affirmativeResponse8 = "Outlook good.";
string affirmativeResponse9 = "Yes.";
string affirmativeResponse10 = "Signs point to yes.";
string nonCommittalResponse1 = "Reply hazy, try again.";
string nonCommittalResponse2 = "Ask again later.";
string nonCommittalResponse3 = "Better not tell you now.";
string nonCommittalResponse4 = "Cannot predict now.";
string nonCommittalResponse5 = "Concentrate and ask again.";
string negativeResponse1 = "Don't count on it.";
string negativeResponse2 = "My reply is no.";
string negativeResponse3 = "My sources say no.";
string negativeResponse4 = "Outlook not so good.";
string negativeResponse5 = "Very doubtful.";
int numberOfResponse;
Random var = new Random();
numberOfResponse = var.Next(20);
switch (numberOfResponse)
{
case 0:
response = affirmativeResponse1;
return response;
case 1:
response = affirmativeResponse2;
return response;
case 2:
response = affirmativeResponse3;
return response;
case 3:
response = affirmativeResponse4;
return response;
case 4:
response = affirmativeResponse5;
return response;
case 5:
response = affirmativeResponse6;
return response;
case 6:
response = affirmativeResponse7;
return response;
case 7:
response = affirmativeResponse8;
return response;
case 8:
response = affirmativeResponse9;
return response;
case 9:
response = affirmativeResponse10;
return response;
case 10:
response = nonCommittalResponse1;
return response;
case 11:
response = nonCommittalResponse2;
return response;
case 12:
response = nonCommittalResponse3;
return response;
case 13:
response = nonCommittalResponse4;
return response;
case 14:
response = nonCommittalResponse5;
return response;
case 15:
response = negativeResponse1;
return response;
case 16:
response = negativeResponse2;
return response;
case 17:
response = negativeResponse3;
return response;
case 18:
response = negativeResponse4;
return response;
case 19:
response = negativeResponse5;
return response;
default:
response = affirmativeResponse1;
return response;
}
}
} ```
When you return a value from a function, nothing after that return can be ran - you're leaving the function. Therefore the breaks will never be reached because there is always a return right before them.
You also don't need to assign the return value to the response variable, you can just write
return affirmativeResponseX;
This is because when you return, you exit the function. It will never reach the break because you return right before it. The fix is simple. Just remove the breaks.
I want to know if my gridView is empty-doesn't have any items in it.
I have tried to do the following :
public sealed partial class Profile : Page
{
Boolean isGridViewEmpty = true;
}
This is the function that shows the grid view, and I have tried to make it also determine whether or not the gridview is empty
//gets the animals of the specific chosen user's data tabe
public async void getAnimalsData(int ownerId)
{
int count = 0;
regitration.getAnimalsOfUserTableResponseGetAnimalsOfUserTableResult r = await cal.getAnimalsOfUserTableAsync(ownerId);
List<Animal> theAnimalList = new List<Animal>();
Animal a = null;
XmlReader xr = r.Any1.CreateReader();
XmlDocument document = new XmlDocument();
document.Load(xr);
XmlNodeList theXmlList = document.GetElementsByTagName("Table");
foreach (XmlElement item in theXmlList)
{
a = new Animal();
foreach (XmlNode node in item.ChildNodes)
{
switch (node.Name)
{
case "animalId": a.AnimalId = int.Parse(node.InnerText); count++; break;
case "ownerId": a.OwnerId = int.Parse(node.InnerText); count++; break;
case "animalName": a.Animalname = node.InnerText; count++; break;
case "fur": a.Fur = node.InnerText; count++; break;
case "level": a.Level = int.Parse(node.InnerText); count++; break;
case "money": a.Money = int.Parse(node.InnerText); count++; break;
}
}
theAnimalList.Add(a);
}
grid2.ItemsSource = theAnimalList;
if (count == 0)
{
isGridViewEmpty = true;
}
else
{
isGridViewEmpty = false;
}
}
Upon debugging, I could see that it doesn't really exit the function, although, it also doesn't display an error message. It just appears stuck after the last curly bracket.
I have no idea what I'm doing wrong, the count appears to work fine , upon debugging it also shows me that isGridViewEmpty is really set to true, but whenever I come to implement the function and I check if isGridViewEmptyis true, it doesn't work. Also, as I mentioned before, the debugger gets stuck in the function getAnimalsData
The function getAnimalsData was async. So it actually works, just because it happens in the background instead of the order I pressed it, so whenever I have conditional related functionality, it looks useless. So I made it a Task instead of void and put await before the function.
For more detail you could refer Asynchronous programming with async and await (C#).
I'm writing this simple code in html:-
<a id="{{L.ID}}" target="_blank" href="/Home/RedirectToMaterialView?MaterialTypeID={{L.MaterialTypeID}}&SearchListID={{L.SearchListID}}&Category={{L.Category}}" style="cursor:pointer">Open</a>
Now this goes to my HomeController and works perfect in my local machine, where I redirect it to some other actionlink. c# controller actionresult is like this:-
public ActionResult RedirectToMaterialView(string MaterialTypeID, string SearchListID, string Category)
{
if (!string.IsNullOrEmpty(SearchListID))
{
dbundle.MaterialFetchID = Convert.ToInt32(SearchListID);
dbundle.MaterialIndicator = Convert.ToInt32(MaterialTypeID);
dbundle.MaterialFor = Convert.ToString(Category);
string queryString = string.Empty;
TempData["DBundle"] = dbundle;
switch (dbundle.MaterialFor)
{
case "Class":
switch (dbundle.MaterialIndicator)
{
case 1:
TempData["ClassMaterialHeading"] = Constants.EBook;
break;
case 2:
TempData["ClassMaterialHeading"] = Constants.Notes;
break;
default:
TempData["ClassMaterialHeading"] = "";
break;
}
return RedirectToAction(Constants.ClassMaterial, new { id= dbundle.MaterialFetchID, MatFor =dbundle.MaterialFor});
case "Degree":
switch (dbundle.MaterialIndicator)
{
case 1:
TempData["DegreeMaterialHeading"] = Constants.EBook;
break;
case 2:
TempData["DegreeMaterialHeading"] = Constants.Notes;
break;
default:
TempData["DegreeMaterialHeading"] = "";
break;
}
return RedirectToAction(Constants.DegreeMaterial, new { id = dbundle.MaterialFetchID, MatFor = dbundle.MaterialFor });
default:
return RedirectToAction(Constants.School);
}
}
else
return RedirectToAction(Constants.Degree);
}
But when I run this code on server. It's redirecting to a blank page.
I don't know what's creating problem. Maybe I'm missing something in the link. But I can't figure out what's the problem on server which is not on my machine.
Help Appreciated.
I'm new to asp.net mvc & I'm trying to make a website where user can sort a table after login. When I build the project I get errors like, Does not contain a definition for 'OrderByDescending'/'OrderBy'/'ToList'. Here are my codes,
Controller
ViewBag.CodeSort = String.IsNullOrEmpty(sortOrder) ? "code_desc" : "";
var sortedOut = new MkistatVsUserLogin { mkistats = dsedb.mkistats.AsQueryable() }; //Error in this line
switch (sortOrder)
{
case "code_desc":
sortedOut = sortedOut.OrderByDescending(s => s.MKISTAT_CODE); //error in this line
break;
default:
sortedOut = sortedOut.OrderBy(s => s.MKISTAT_CODE); //error in this line
break;
}
return View(sortedOut.ToList()); //error in this line
Model
public class MkistatVsUserLogin
{
public IQueryable<mkistat> mkistats { get; set; }
public idx Idxs { get; set; }
}
How can I solve this problem? Need this help badly. Tnx.
Because the IQueryable is the mkistats, not the sortedOut!
ViewBag.CodeSort = String.IsNullOrEmpty(sortOrder) ? "code_desc" : "";
var sortedOut = new MkistatVsUserLogin { mkistats = dsedb.mkistats.AsQueryable() }; //Error in this line
switch (sortOrder)
{
case "code_desc":
sortedOut.mkistats = sortedOut.mkistats.OrderByDescending(s => s.MKISTAT_CODE); //error in this line
break;
default:
sortedOut.mkistats = sortedOut.mkistats.OrderBy(s => s.MKISTAT_CODE); //error in this line
break;
}
return View(sortedOut); //error in this line
And the switch is wrong, but I am not sure how to solve it. It should probably be
switch (ViewBag.CodeSort)
Note that as the code is written, the view will only receive a List<mkistat>, not a full MkistatVsUserLogin object.
OrderByDescending is an extension method inside of System.Linq.
Make sure you have the relevant using statemenet at the top of your class
using System.Linq;
I'm doing an C# app where I use
if ((message.Contains("test")))
{
Console.WriteLine("yes");
} else if ((message.Contains("test2"))) {
Console.WriteLine("yes for test2");
}
There would be any way to change to switch() the if() statements?
Correct final syntax for [Mr. C]s answer.
With the release of VS2017RC and its C#7 support it works this way:
switch(message)
{
case string a when a.Contains("test2"): return "no";
case string b when b.Contains("test"): return "yes";
}
You should take care of the case ordering as the first match will be picked. That's why "test2" is placed prior to test.
Nope, switch statement requires compile time constants. The statement message.Contains("test") can evaluate true or false depending on the message so it is not a constant thus cannot be used as a 'case' for switch statement.
If you just want to use switch/case, you can do something like this, pseudo-code:
string message = "test of mine";
string[] keys = new string[] {"test2", "test" };
string sKeyResult = keys.FirstOrDefault<string>(s=>message.Contains(s));
switch (sKeyResult)
{
case "test":
Console.WriteLine("yes for test");
break;
case "test2":
Console.WriteLine("yes for test2");
break;
}
But if the quantity of keys is a big, you can just replace it with dictionary, like this:
static Dictionary<string, string> dict = new Dictionary<string, string>();
static void Main(string[] args)
{
string message = "test of mine";
// this happens only once, during initialization, this is just sample code
dict.Add("test", "yes");
dict.Add("test2", "yes2");
string sKeyResult = dict.Keys.FirstOrDefault<string>(s=>message.Contains(s));
Console.WriteLine(dict[sKeyResult]); //or `TryGetValue`...
}
This will work in C# 8 using a switch expresion
var message = "Some test message";
message = message switch
{
string a when a.Contains("test") => "yes",
string b when b.Contains("test2") => "yes for test2",
_ => "nothing to say"
};
For further references
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/switch-expression
Simple yet efficient with c#
string sri = "Naveen";
switch (sri)
{
case var s when sri.Contains("ee"):
Console.WriteLine("oops! worked...");
break;
case var s when sri.Contains("same"):
Console.WriteLine("oops! Not found...");
break;
}
string message = "This is test1";
string[] switchStrings = { "TEST1", "TEST2" };
switch (switchStrings.FirstOrDefault<string>(s => message.ToUpper().Contains(s)))
{
case "TEST1":
//Do work
break;
case "TEST2":
//Do work
break;
default:
//Do work
break;
}
You can do the check at first and then use the switch as you like.
For example:
string str = "parameter"; // test1..test2..test3....
if (!message.Contains(str)) return ;
Then
switch(str)
{
case "test1" : {} break;
case "test2" : {} break;
default : {} break;
}
Faced with this issue when determining an environment, I came up with the following one-liner:
string ActiveEnvironment = localEnv.Contains("LIVE") ? "LIVE" : (localEnv.Contains("TEST") ? "TEST" : (localEnv.Contains("LOCAL") ? "LOCAL" : null));
That way, if it can't find anything in the provided string that matches the "switch" conditions, it gives up and returns null. This could easily be amended to return a different value.
It's not strictly a switch, more a cascading if statement but it's neat and it worked.
Some custom swtich can be created like this. Allows multiple case execution as well
public class ContainsSwitch
{
List<ContainsSwitch> actionList = new List<ContainsSwitch>();
public string Value { get; set; }
public Action Action { get; set; }
public bool SingleCaseExecution { get; set; }
public void Perform( string target)
{
foreach (ContainsSwitch act in actionList)
{
if (target.Contains(act.Value))
{
act.Action();
if(SingleCaseExecution)
break;
}
}
}
public void AddCase(string value, Action act)
{
actionList.Add(new ContainsSwitch() { Action = act, Value = value });
}
}
Call like this
string m = "abc";
ContainsSwitch switchAction = new ContainsSwitch();
switchAction.SingleCaseExecution = true;
switchAction.AddCase("a", delegate() { Console.WriteLine("matched a"); });
switchAction.AddCase("d", delegate() { Console.WriteLine("matched d"); });
switchAction.AddCase("a", delegate() { Console.WriteLine("matched a"); });
switchAction.Perform(m);
Stegmenn nalied it for me, but I had one change for when you have an IEnumerable instead of a string = message like in his example.
private static string GetRoles(IEnumerable<External.Role> roles)
{
string[] switchStrings = { "Staff", "Board Member" };
switch (switchStrings.FirstOrDefault<string>(s => roles.Select(t => t.RoleName).Contains(s)))
{
case "Staff":
roleNameValues += "Staff,";
break;
case "Board Member":
roleNameValues += "Director,";
break;
default:
break;
}
}
This will work in C# 7. As of this writing, it has yet to be released. But if I understand this correctly, this code will work.
switch(message)
{
case Contains("test"):
Console.WriteLine("yes");
break;
case Contains("test2"):
Console.WriteLine("yes for test2");
break;
default:
Console.WriteLine("No matches found!");
}
Source: https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/
switch(message)
{
case "test":
Console.WriteLine("yes");
break;
default:
if (Contains("test2")) {
Console.WriteLine("yes for test2");
}
break;
}