I just want to calculate your future age. You enter 3 things: your current age, the current year, and the future year. I was experiementing with for and do while loops. Then I came cross this problem, variable currentAge is not initialized. But none of the other variables are initialized either, other variables are fine. The only difference here is others are in the do while loop, but currentAge is in the for loop. Why did this happen? Can somebody explain the difference and why? Please see the below code.
import java.util.Scanner;
public class Lab3Class
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
String cleanUpStr;
int currentAge;
int futureAge;
int currentYear;
int futureYear;
for (int cntr = 0; cntr < 3; ++cntr)
{
System.out.print("Enter your current age\t");
currentAge = input.nextInt( );
cleanUpStr = input.nextLine( );
}
if (currentAge >= 0){
do
{
System.out.print("Enter current year\t");
currentYear = input.nextInt( );
cleanUpStr = input.nextLine( );
} while(currentYear < 0);
do
{
System.out.print("Enter future year\t");
futureYear = input.nextInt( );
cleanUpStr = input.nextLine( );
} while(futureYear < 0 || futureYear < currentYear);
input.close();
futureAge = currentAge + (futureYear - currentYear);
System.out.println("In the year " + currentYear + " you are " + currentAge + " years old");
System.out.println("In the year " + futureYear + " you will be " + futureAge + " years old");
} else {
System.out.println("Too many tries for an valid age!");
}
}
}