Consider the following:
package senioreligible;
import java.time.Year;
import java.util.*;
public class SeniorEligible {
public static void main(String[] args) {
System.out.print("Enter your Year of Birth: ");
Scanner in = new Scanner(System.in);
int birthYear = in.nextInt();
int age = Year.now().getValue() - birthYear;
System.out.println("Your are " age " years old.");
if (age>=60) {
System.out.println("You are eligble to be senior citizen.");
}
else {
System.out.println("You are not eligible to be senior citizen.");
}
}
}
I have a sample code working but the problem is how to use functions and objects in this syntax
CodePudding user response:
import java.util.*;
import java.time.format.DateTimeFormatter;
import java.time.LocalDateTime;
public class Main
{
public static void main (String[]args)
{
System.out.print ("Enter your BirthYear-");
Scanner in = new Scanner (System.in);
int birthYear = in.nextInt ();
LocalDateTime now = LocalDateTime.now ();
// System.out.println (now.getYear ());
int age = now.getYear () - birthYear;
System.out.println ("Your are " age " years old.");
if (age >= 60)
{
System.out.println ("You are eligble to be senior citizen.");
}
else
{
System.out.println ("You are not eligible to be senior citizen.");
}
}
}
CodePudding user response:
Same program with function.
import java.time.LocalDate;
import java.time.Period;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.print("Enter your Date of birth-");
Scanner in = new Scanner(System.in);
int birthYear = in.nextInt();
int birthMonth = in.nextInt();
int birthDay = in.nextInt();
calAge(birthYear,birthMonth,birthDay);
}
static void calAge(int birthYear,int birthMonth, int birthDay) {
LocalDate birthday = LocalDate.of(birthYear, birthMonth, birthDay);
Period p = Period.between(birthday, LocalDate.now());
System.out.println("Your are " p.getYears() " years old.");
if (p.getYears() >= 60) {
System.out.println("You are eligible to be senior citizen.");
} else {
System.out.println("You are not eligible to be senior citizen.");
}
}
}
CodePudding user response:
I would suggest to create a method(function) in the program and create an object of the class in the main method and then call the method of the user-defined class which takes input for the birthyear. The code below is working correctly now.
import java.time.Year;
import java.util.*;
public class SeniorEligible {
private int birthYear;
public SeniorEligible() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your Year of Birth: ");
birthYear = sc.nextInt();
sc.close();
}
public static void main(String[] args) {
SeniorEligible ob = new SeniorEligible();
int age = Year.now().getValue() - ob.birthYear;
System.out.println("Your are " age " years old.");
if (age >= 60) {
System.out.println("You are eligble to be senior citizen.");
} else {
System.out.println("You are not eligible to be senior citizen.");
}
}
}