Jibril Nadela
Jibril Nadela

Reputation: 1

Create a java loop that calculates the age of the user when he/she inputs a birth year, any ideas?

I am complying a project in computer programming and is new to programming, our professor wants us to 'write a program with loop that will calculate the year of the user and outputs his/her age'.

import java.util.Scanner;
import java.util.Calendar;

public class lisuuh {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int year = Calendar.getInstance().get(Calendar.YEAR);
        int myyear, result;


    do{
        System.out.print("Enter your birth year: ");
        myyear = sc.nextInt();

        result = myyear - year;
    }while(result == result);
    System.out.print("You are "+result+"year/s old.");


    }
}

Expected output:

Enter a Year: 2010

You are 9 Year/s old.

Upvotes: 0

Views: 868

Answers (1)

Shashini Prabodha
Shashini Prabodha

Reputation: 190

Your answer should change like this:

import java.util.Scanner;
import java.util.Calendar;

public class lisuuh {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int year = Calendar.getInstance().get(Calendar.YEAR);
        int myyear, result;
        do {
            System.out.print("Enter your birth year: ");
            myyear = sc.nextInt();
            result = myyear - year;
        } while(result>0); // this line changed
            System.out.println("You are "+result+"year/s old.");//line changed


    }
}

Upvotes: 0

Related Questions