Java algorithm, age increase;

Asked

Viewed 175 times

0

I wanted to know how to make an algorithm in which I inserted a year, and the value increased with age, as year 2016=1, year 2017 = 2, in a method.

Something like that:

int fazAniversidade(int ano) {
    if(ano == 2015) {
        this.idade +=1;
    }
    if(ano == 2016) {
        this.idade +=2;
    }

    return 0;

 }

But in a loop, how to do?

  • What rule will you use to increase the year? Will you read the time in the system or is it just a test?

  • 1

    I think you could put more details, try to clarify your doubt.

1 answer

6

  1. It makes no sense to return 0 (zero) if the intention is only to set this.idade = x. In this case, use void in function.
  2. No need to use loop, just pick the difference between the current year and the year reported in the function call.

Upshot

Main.java

import java.util.Calendar;

public class Main
{

    static int idade;

    public static void main(String[] args)
    {
        idade = 10;
        fazAniversidade(2015); // seta idade = 11
        //fazAniversidade(2016); // seta idade = 12
        //fazAniversidade(2017); // seta idade = 13
    }

    public static void fazAniversidade(int ano)
    {
        int ano_atual = Calendar.getInstance().get(Calendar.YEAR);
        int diferenca = (ano - ano_atual) + 1;

        idade += diferenca;
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.