Reputation: 307
I used this program to my purpose. import java.util.Scanner;
class NIC_Details {
String id;
int month[] = {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
NIC_Details() {
Scanner input = new Scanner(System.in);
System.out.println("Enter Your NIC Number \nLike : 000000000V");
id = input.next();
}
int getYear() {
return (1900 + Integer.parseInt(id.substring(0, 2)));
}
int getDays() {
int d = Integer.parseInt(id.substring(2, 5));
if (d > 500) {
return (d - 500);
} else {
return d;
}
}
public void setMonth() {
int mo = 0, da = 0;
int days = getDays();
for (int i = 0; i < month.length; i++) {
if (days < month[i]) {
mo = i + 1;
da = days;
break;
} else {
days = days - month[i];
}
}
System.out.println("Month : " + mo + "\nDate : " + da);
}
public String getSex() {
String M = "Male", F = "Female";
int d = Integer.parseInt(id.substring(2, 5));
if (d > 500) {
return F;
} else {
return M;
}
}
public static void main(String[] args) {
NIC_Details N = new NIC_Details();
System.out.println("Your Details of Date of Birth from NIC Number");
System.out.println("Year : " + N.getYear());
N.setMonth();
System.out.println("Sex : " + N.getSex());
}
}
but when I enter a NIC number like this 93031*** It gives this details
Enter Your NIC Number
Like : 000000000V
93031******
Your Details of Date of Birth from NIC Number
Year : 1993
Month : 2
Date : 0
Sex : Male
Please show me what happen here.
Upvotes: 3
Views: 5145
Reputation: 11577
Your code is ok, it's your logic that has problem.
Your input is 31 days. Your setMonth()
method asks if days < month[i]
, when month[0]==31
.
The answer is no, then you do days = days - month[i];
which makes days = 0
, and month = 2
.
you might want to change your if statement to:
if (days <= month[i]) {
but that depends on weather 31 days means that 31 days passed, and then your code is good the way it is
Upvotes: 1