-2

I'm trying to do some validation for a user entered date. Is there a way to have multiple || statements and then an encompassing && statement for them all? Here's my code:

if (month == 4 || month == 6 || month == 9 || month == 11 && day < 31 && day > 0)

As of right now the && statements only apply to the month == 11 variable. Is there an easy fix to using && in this if statement (without having to copy/paste it after every variable)?

giorashc
  • 13,691
  • 3
  • 35
  • 71
  • 9
    Yes, parentheses. – Turing85 Oct 10 '16 at 12:26
  • Yuck. There are better ways of checking if a date is actually valid. How will you handle leap years for example? Or wierd months like 1752 in England. See http://stackoverflow.com/questions/999172/how-to-parse-a-date – Bathsheba Oct 10 '16 at 12:28
  • 4
    I don't agree with the downvotes. It may be a trivial question to most programmers, but other than that there's not much wrong with it. It's to the point, clear and concise. – wvdz Oct 10 '16 at 12:34

5 Answers5

2

Just use parentheses:

if ((month == 4 || month == 6 || month == 9 || month == 11) && day < 31 && day > 0)
Filipp Voronov
  • 4,077
  • 5
  • 25
  • 32
0

You can use parentheses to force precedence.

if((month == 4 || month == 6 || month == 9 || month == 11) && day < 31 && day > 0)

Keenan Lawrence
  • 1,446
  • 10
  • 16
0
if ( (month == 4 || month == 6 || month == 9 || month == 11) && (day < 31 && day > 0))

Brackets are your friend

Ash
  • 2,562
  • 11
  • 31
0

One set of parentheses around all the month || statements will achieve that.

if ( (month == 4 || month == 6 || month == 9 || month == 11 ) && day < 31 && day > 0)

Now it evaluates as if(month4,6,9,11 && day<31 && day>0)

JynXXedRabbitFoot
  • 996
  • 1
  • 7
  • 17
-1

if ((month == 4 || month == 6 || month == 9 || month == 11) && (day < 31 && day > 0))