aplicación Calendario: molestia de añadir días a la fecha

i_want_to_code:

Mi tarea es: Implementar el método de avance public void () que se mueve la fecha por un día. En este ejercicio se supone que cada mes tiene 30 días. ¡NÓTESE BIEN! En ciertas situaciones es necesario cambiar los valores de mes y año.

He hecho esto:

public class SimpleDate {

    private int day;
    private int month;
    private int year;

    public SimpleDate(int day, int month, int year) {
        this.day = day;
        this.month = month;
        this.year = year;
    }

    @Override
    public String toString() {
        return this.day + "." + this.month + "." + this.year;
    }

    public boolean before(SimpleDate compared) {
        if (this.year < compared.year) {
            return true;
        }

        if (this.year == compared.year && this.month < compared.month) {
            return true;
        }

        if (this.year == compared.year && this.month == compared.month &&
                 this.day < compared.day) {
            return true;
        }

        return false;
    }

    public void advance(){
        if(this.day<30){
            this.day += 1;
        }    
        if(this.day==30 && this.month==12){
            this.day = 1;
            this.month=1;
            this.year +=1;
        }
        if(this.day==30){
            this.day = 1;
            this.month +=1;
        }
    }

    public void advance(int howManyDays){
        if(howManyDays < 30){
            if(this.day<30 && (this.day + howManyDays < 30)){
                this.day += howManyDays;
            }
            if(this.day==30 && this.month==12){
                this.day = howManyDays;
                advance();
            }
            if(this.day==30){
                this.day = howManyDays;
                this.month +=1;
            } 
        }
        if(howManyDays== 30 && this.month==12){
            this.day = howManyDays;
            advance();
        }
        if(howManyDays == 30){
            this.month += 1;
        }
    }
    public SimpleDate afterNumberOfDays(int days){

        SimpleDate obj = new SimpleDate(days, this.month,this.year);
        return obj;

    }

}

Pero cuando lo prueba con:

SimpleDate date = new SimpleDate(30, 12, 2011);  date.advance(3);

Ahora, la fecha debe ser 3.1.2012. se esperaba: [3.1.2012]pero fue:[4.12.2011]

Tim Hunter:

Te recomiendo simplificar su enfoque en esto con whilebucles en lugar de lo múltiple y anidados ifdeclaraciones ...

public void advance(int howManyDays) {
  this.day += howManyDays;

  //Subtracts out the days till within range, incrementing months
  while(this.day > 30) {
    this.day -= 30;
    this.month++;
  }

  //Subtracts out the months till within range, incrementing years
  while(this.month > 12) {
    this.month -= 12;
    this.year++;
  }
}

Supongo que te gusta

Origin http://10.200.1.11:23101/article/api/json?id=396854&siteId=1
Recomendado
Clasificación