java – 如何分配在if else语句中定义的变量
发布时间:2020-12-15 05:21:34 所属栏目:Java 来源:网络整理
导读:我需要创建能够在GMT中找到当前小时并将其转换为EST的内容. 当我尝试编译并运行程序时,我收到此错误:currentHourEST无法解析为变量.我认为我的问题是if else语句中的某个地方,因为我将变量分配给了错误或其他东西. // Obtain total milliseconds since midn
我需要创建能够在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. 解决方法
if块中定义的变量仅限于if块,你根本不能使用if块之外的变量.
如果你想在一个if块外面使用一个变量,只要在块外面声明它. // If the time is negative make it a positive long currentHourEST; if (offSetAdded > 0) { currentHourEST = offSetAdded * -1; } else { currentHourEST = offSetAdded; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |