2017-02-23 3 views
3

J'écris un code qui doit répondre à une condition préalable, et si les conditions sont toutes remplies, alors il retournera vrai. J'ai essayé plusieurs "si" des déclarations, mais cela ne semble pas fonctionner. Si les instructions imbriquées ne semblent pas être la réponse ici, je ne pense pas que les instructions «else if» fonctionneraient. Ce que je demande est, quelle est la bonne façon de faire cela? est-ce que j'écris les affirmations fausses?Comment demander plusieurs conditions pour renvoyer true Java

Heres mon code:

public static boolean isLegitimate(int mon, int day, int year){ 

    // February has 29 days in any year evenly divisible by four, 
    // EXCEPT for centurial years which are not also divisible by 400. 


    // TODO 1: Check if a date is valid. 

    //checks to see if the months are between 1 and 12 
    if((mon >= 1) && (mon <= 12)) { 

    } 
    //checks to see if the years are greater than 1 
    if (year > 0){ 

    } 
    //checks to see if the days are between 1 and 31 
    if ((day >=0) && (day <=31)){ 

    } 

    //This checks that if the month is February, is divisible by 4 evenly, 
    //and is divisible by 100 evenly, then the days can not exceed 29 
    if ((mon == 2) && (year%4==0) && (!(year%100==0)) || (year%400==0)){ 
     if (day >29){ 
      return false; 
     } 
    } 

    return true; 
} 
+1

Si plusieurs conditions doivent toutes être vraies, utilisez l'opérateur && entre les conditions. –

Répondre

5

Renvoyez juste faux si une vérification échoue. Si l'une des conditions préalables échoue, il n'est pas nécessaire de vérifier davantage.

public static boolean isLegitimate(int mon, int day, int year){ 

    // February has 29 days in any year evenly divisible by four, 
    // EXCEPT for centurial years which are not also divisible by 400. 

    // TODO 1: Check if a date is valid. 

    //checks to see if the months are between 1 and 12 
    if(mon<1) return false; 
    if(mon>12) return false; 

    //checks to see if the years are greater than 1 
    if(year<=0) return false; 

    //checks to see if the days are between 1 and 31 
    if(day<=0) return false; 
    if(day>31) return false; 

    //This checks that if the month is February, is divisible by 4 evenly, 
    //and is divisible by 100 evenly, then the days can not exceed 29 
    if ((mon == 2) && (year%4==0) && (!(year%100==0)) || (year%400==0)){ 
     if (day >29){ 
      return false; 
     } 
    } 
    return true; 
} 
+0

'si (jour <0)' ??? Donc, le 0 février est cool? ;-) – mcalex

+0

Je suppose que je suis compatible avec le code original. :-) Je répare. –

+0

oups, quand j'ai lu son code, j'ai juste vu 'jour> 0'. Doit avoir écrémé trop vite. Ignorer mon commentaire précédent. Bien que je ne sois pas sûr que le changement fonctionne non plus. Je pense que tu veux '(jour <1) ';-) – mcalex

0

Vous pouvez utiliser le JodaTime API

public static boolean isLegitmate(int mon, int day, int year){ 
    try { 
     new DateTime().withMonthOfYear(mon).withYear(year).withDayOfMonth(day); 
     return true; 
    } catch (Exception e){ 
     return false; 
    } 
} 
0

Essayez ceci:

public static boolean isLegitimate(int mon, int day, int year){ 

if( (mon >= 1 && mon <= 12) && (year > 0) && (day >=0 && day <=31)){ 
    if ((mon == 2) && (year%4==0) && (!(year%100==0)) || (year%400==0)) 
    if (day >29) 
     return false; 
    return true; 
} 
} 
1

Ajouter une variable booléenne en haut de votre code:

bool legit = true; 

Dans chaque instruction if, si la condition est fausse, changez la valeur de légitime. Ne le changez pas si la valeur est vraie.

A la fin des conditions, la variable retour:

return legit; 

Si des contrôles ne sont pas légitimes, la méthode wil return false.

Edit: la solution de Espen est plus efficace (si un peu moins précis - voir le commentaire), bien que j'avais OR les deux clauses:

if((mon < 1) || (mon>12)) return false; 

et

if((day < 1) || (day > 31)) return false; 

Notez cependant que cette peut toujours renvoyer des dates non valides comme valides, par exemple: 31 juin

+0

l'autre solution peut être plus efficace, mais je ne comprends pas pourquoi les gens downvoted votre réponse, c'est vrai. –

0

Cela éclate votre logique en plusieurs méthodes. J'ai modifié un peu la logique de l'année bissextile.

public class MultipleConditions { 

    public static boolean isLegitimate(int mon, int day, int year) { 


     return validMonth(mon) && validYear(year) && validDay(day) && validFebDay(mon, day, year); 
    } 

    private static boolean validFebDay(int mon, int day, int year) { 
     // February has 29 days in any year evenly divisible by four, 
     // EXCEPT for centurial years which are not also divisible by 400. 
     if (mon!=2) 
      return true; // Not in feb 
     if (year%4 != 0) 
      return day <= 28; // Not a leap year 

     if (year%100 == 0) { 
      return day <= 29; // Divisible by 4, but not a centurial year 
     } 
     // Divisible by 4, centurial year, and divisible by 400 
     if (year%400==0) { 
      return day <=29; 
     } 
     // Divisible by 4, centurial year not divisible by 400 
     return day <= 28; 
    } 

    private static boolean validDay(int day) { 
     // checks to see if the days are between 1 and 31 
     return day >= 0 && day <= 31; 
    } 

    private static boolean validYear(int year) { 
     return year > 0; 
    } 

    private static boolean validMonth(int mon) { 
     // checks to see if the months are between 1 and 12 
     return (mon >= 1) && (mon <= 12); 
    } 
    public static void main(String args []) { 
     System.out.println(isLegitimate(2, 23, 2017)); 
     System.out.println(isLegitimate(2,29,2017)); 
     System.out.println(isLegitimate(3,31,2017)); 
    } 
}