如何分配在if else语句中定义的变量

rct*_*999 3 java if-statement

我需要创建一些能够在GMT中找到当前小时并将其转换为EST的东西.

当我尝试编译并运行程序时,我收到此错误:currentHourEST cannot be resolved to a variable.我认为我的问题if 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);
Run Code Online (Sandbox Code Playgroud)

我正在使用if else语句来复制offSetAddedby,-1以便小时,如果5从我减去它时它是负数,它变为正数,使人们更容易看到小时.如果offSetAdded是正数,那么它将打印currentHour刚刚减去5.

PaR*_*RaJ 7

if块内定义的变量仅限于if block您不能在if块之外使用变量.

如果你想在一个if块外面使用一个变量,只要在块外面声明它.

// If the time is negative make it a positive
long currentHourEST;
if (offSetAdded > 0) {
 currentHourEST = offSetAdded * -1;
} else {
 currentHourEST = offSetAdded;
}
Run Code Online (Sandbox Code Playgroud)


Tom*_*Tom 6

将您的代码更改为:

// If the time is negative make it a positive
long currentHourEST;
if (offSetAdded > 0) {
    currentHourEST = offSetAdded * -1;
} else {
    currentHourEST = offSetAdded;
}
Run Code Online (Sandbox Code Playgroud)

这将声明块的变量currentHourESToutsite if/else,因此您可以在方法的其余代码中使用它.

您当前的代码声明该块内的变量,这意味着如果程序存在块,则其生命周期结束if/else.因此,您以后无法访问它.

阅读本教程有关变量范围的信息,以了解更多相关信息.