I want to return the number of a month and i made a function but it always returns 0
this is my code:
public int getNrMonth(String s)
{
int nr=0;
if (s.Equals("January"))
nr = 1
if (s.Equals("February"))
nr = 2;
return nr;
}
Could someone tell me wath is wrong please? I'm beginner!
Algorithm. Step 1: Declare three sides of triangle. Step 2: Enter three sides at run time. Step 3: If side1 == side2 && side2 == side3 Go to step 6 Step 4: If side1 == side2 || side2 == side3 || side3 == side1 Go to Step 7 Step 5: Else Go to step 8 Step 6: Print the triangle is equilateral.
Why wouldn't you use the built in function:
DateTime.ParseExact(monthName, "MMMM", CultureInfo.CurrentCulture ).Month
Here is an example on use:
How to parse a month name (string) to an integer for comparison in C#?
It'd be better to do it like this:
switch (s.Trim().ToUpper())
{
case "JANUARY": return 1;
case "FEBRUARY": return 2;
// etc.
}
return 0;
Reasons:
switch
is optimized to begin with (small point, but worth mentioning).if
checks are pointless.Trim()
and ToUpper()
calls will take care of that.OK, you're a beginner, but you still have tools at your disposal. Set a breakpoint and step through in the debugger. Take a look at the value of s
and nr
as you do. Notice which if
statements execute the nr =
part and which you don't. Then you will understand. As it stands I don't think you pasted your real code in, because your question is missing a semi colon and might not even compile.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With