Java – how to allocate variables defined in if else statements
I need to create content that can find the current hour in GMT and convert it to EST
When I try to compile and run the program, I receive this error: currenthousest cannot be resolved to a variable I think my problem is somewhere in the if else statement because I assigned variables to errors or something else
// Obtain total milliseconds since midnight,Jan 1,1970
long totalMilliseconds = System.currentTimeMillis();
// Seconds
long totalSeconds = totalMilliseconds / 1000;
long currentSecond = totalSeconds % 60;
// Minutes
long totalMinutes = totalSeconds / 60;
long currentMinute = totalMinutes % 60;
// Hours
long totalHours = totalMinutes / 60;
long currentHour = totalHours % 24;
// Read in EST offset
long offSetAdded = currentHour - 5;
// If the time is negative make it a positive
if (offSetAdded > 0) {
long currentHourEST = offSetAdded * -1;
} else {
long currentHourEST = offSetAdded;
}
// Display time
System.out.println("The current time is " + currentHourEST + ":" + currentMinute + ":" + currentSecond);
System.out.println("Current time in GMT is " + currentHour + ":" + currentMinute + ":" + currentSecond);
I'm using the if else statement to multiply offsetadded by - 1 so that the hours become positive if you subtract 5 from me, making it easier for people to see the hours If offsetadded is positive, it will print the current exactly minus 5
Solution
The variables defined in the if block are limited to the if block. You can't use variables outside the if block at all
If you want to use a variable outside an if block, just declare it outside the block
// If the time is negative make it a positive
long currentHourEST;
if (offSetAdded > 0) {
currentHourEST = offSetAdded * -1;
} else {
currentHourEST = offSetAdded;
}
