Help...Why won't this compile?
Why won't this compile?
Here is my code:
import java.util.Calendar;
import javax.swing.JOptionPane;
publicclass GetAge{
publicstaticvoid main(String[] args){
int month=Integer.parseInt(JOptionPane.showInputDialog
(null,"Enter what month(MM) you were born:"));
int day=Integer.parseInt(JOptionPane.showInputDialog
(null,"Enter what day(dd) you were born:"));
int year=Integer.parseInt(JOptionPane.showInputDialog
(null,"Enter what year(yyyy) you were born:"));
Calendar rightNow = Calendar.getInstance();
int year2 = rightNow.get(Calendar.YEAR);
int day2 = rightNow.get(Calendar.DATE);
int month2 = rightNow.get(Calendar.MONTH)+1;
int years = year2-year-1;
int months = month2-month+12;
if(day2 >= day)
int days = day2-day;
else
days = day-day2+8;
JOptionPane.showMessageDialog(null,"You are: " + years
+" years " + months +" months and " + days +" days old.");
}
}
What you're doing is using days after the if statement; without curly braces only a valid statement is allowed.
But if you add curly braces, days will be available only in the if block.
So what you should do is:
import java.util.Calendar;
import javax.swing.JOptionPane;
public class GetAge{
public static void main(String[] args){
int month=Integer.parseInt(JOptionPane.showInputDialog
(null,"Enter what month(MM) you were born:"));
int day=Integer.parseInt(JOptionPane.showInputDialog
(null,"Enter what day(dd) you were born:"));
int year=Integer.parseInt(JOptionPane.showInputDialog
(null,"Enter what year(yyyy) you were born:"));
Calendar rightNow = Calendar.getInstance();
int year2 = rightNow.get(Calendar.YEAR);
int day2 = rightNow.get(Calendar.DATE);
int month2 = rightNow.get(Calendar.MONTH)+1;
int years = year2-year-1;
int months = month2-month+12;
int days = 0;//declare here
if(day2 >= day)
days = day2-day; //...and use here
else
days = day-day2+8;//..and here
JOptionPane.showMessageDialog(null,"You are: " + years
+ " years " + months + " months and " + days + " days old.");
}
}