I'm quite a beginner when it comes to programming so my problem might seem quite easy for most of people here. I'm trying to make an easy program where you write down a day of the week and it should show an information depending on an answer. I chose Sunday as a correct answer. I tried it with bool, with string but I had a problem with it not converting the answer so I don't really know what to do next. Here's the code.
Boolean day;
Boolean Sunday = true;
Boolean Monday, Tuesday, Wednesday, Thursday, Friday, Saturday = false;
Console.Write("What's the day of the week today? Write your answer here: ");
day = Boolean.Parse(Console.ReadLine());
if (Sunday == true)
{
Console.WriteLine("Your answer is correct!");
}
else
{
Console.WriteLine("Your answer is incorret. Please try again.");
}
Console.ReadKey();
CodePudding user response:
The user input you are expecting is a string
of day of week, but your data type is Boolean
which is either true
or false
.
So when converting from "Sunday" which will be user input for example, the code tries to convert to either true or false and throws exception.
You should write your program this way:
private static void Main(string[] args)
{
var currentDayOfWeek = DayOfWeek.Sunday;
// currentDayOfWeek = DateTime.Today.DayOfWeek; // or if you want dynamically set todays day of week
string userInputDayOfWeek;
Console.Write("What's the day of the week today? Write your answer here: ");
userInputDayOfWeek = Console.ReadLine();
if ((Enum.TryParse(typeof(DayOfWeek), userInputDayOfWeek, ignoreCase: true, out object userInputParsed))
&& (DayOfWeek)userInputParsed == currentDayOfWeek)
{
Console.WriteLine("Your answer is correct!");
}
else
{
Console.WriteLine("Your answer is incorrect. Please try again.");
}
Console.ReadKey();
}
Here we make use of enum DayOfWeek
from the System
namespace and we parse the user input with ignore case flag.
CodePudding user response:
As I understand reflections are out of the scope of your school project, so you can create a string array
string trueDay = "Sunday";
// or maybe better
string trueDay=DateTime.Today.DayOfWeek.ToString();
string[] falseDays = new string[] { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
Console.Write("What's the day of the week today? Write your answer here: ");
var day = Console.ReadLine();
if (day.ToLower() == trueDay.ToLower())
{
Console.WriteLine("Your answer is correct!");
}
else if ( falseDays.Any( d =>d.ToLower()==day.ToLower() ))
{
Console.WriteLine("Your answer is incorret. Please try again.");
} else
Console.WriteLine("Please type a correct day name!");
Console.ReadKey();
if Linq is not allowed too, try this
var found=false;
foreach (var item in falseDays)
{
if (item.ToLower() == day.ToLower())
{
found=true;
Console.WriteLine("Your answer is incorret. Please try again.");
break;
}
}
if(!found) Console.WriteLine("Please type a correct day name!");