如何给在if else语句中定义的变量赋值

3

我需要创建一个程序,可以找到当前的GMT时间,并将其转换为EST时间。

当我尝试编译和运行程序时,我收到了这个错误:currentHourEST无法解析为变量。我认为我的问题可能出现在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);

我正在使用if else语句将offSetAdded乘以-1,这样如果小时数是负数,当我从中减去5时,它就变成正数,使人们更容易看到小时数。如果offSetAdded是正数,则会打印刚刚减去5的currentHour
4个回答

7

if块中定义的变量仅限于该if块中使用,你不能在if块外部使用该变量。

如果想要使某个变量在if块外部使用,只需在if块外部声明即可。

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

6
把你的代码改为以下内容:
// If the time is negative make it a positive
long currentHourEST;
if (offSetAdded > 0) {
    currentHourEST = offSetAdded * -1;
} else {
    currentHourEST = offSetAdded;
}

这将声明变量 currentHourESTif/else 块外部,因此您可以在该方法的其余代码中使用该变量。
您当前的代码在该块内部声明变量,这意味着如果程序退出 if/else 块,它的生命周期也会结束。因此,稍后无法访问它。
阅读这篇关于“变量作用域”的教程,以了解更多信息。

4

我不是专家,无法说明具体原因,但如果你将currentHourEST声明在if语句和else语句之外,代码应该可以运行。 像这样:

long currentHourEST;

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

2

首先,您需要声明变量,然后像这样初始化它:

long currentHourEST;
if (offSetAdded > 0) {
  currentHourEST = offSetAdded * -1;
} else {
  currentHourEST = offSetAdded;
}

或者你可以使用条件运算符(也称为三元运算符)? :
long currentHourEST = (offSetAdded > 0) ? offSetAdded * -1 : offSetAdded;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接