【发布时间】:2018-09-21 06:24:04
【问题描述】:
我正在尝试使用 for 循环来更新先前声明的变量,并且在循环内变量值更新正常(使用 print 语句进行检查)。但是,在循环结束后,如果我在循环外使用 print 语句检查值,它们与循环之前的值相同,并且没有更新以供我在其他地方使用。
public class Intervals {
public static void main(String[] args) {
// Declaring necessary constants
int MINUTES_IN_DAY = 1440;
int MINUTES_IN_HOUR = 60;
// Take user inputs for interval start and end times in hours
Scanner input = new Scanner(System.in);
System.out.print("Enter the earlier interval's start and end time in 24-hour time format. ");
int intervalStart1 = input.nextInt();
int intervalEnd1 = input.nextInt();
System.out.print("Enter the later interval's start and end time in 24-hour time format. ");
int intervalStart2 = input.nextInt();
int intervalEnd2 = input.nextInt();
// For-each loop that converts all 24-hour times to minutes after midnight
int times[] = {intervalStart1, intervalEnd1, intervalStart2, intervalEnd2};
for (int i: times) {
i = (i / 100 * MINUTES_IN_HOUR) + (i % 100);
System.out.println("the interval is " + i);
}
// ERROR: values from for loop are not being saved, so variable values are not being updated as shown in next print line.
System.out.println(intervalStart1);
【问题讨论】:
-
在您的循环中,您更新的唯一值是 i,它是循环范围内的局部变量。一旦循环结束,这个变量就会存在。
-
这是有道理的。有没有办法让我使用循环来全局而不是本地更新变量?
-
您要更新哪个变量?
-
我正在尝试修改数组中的所有变量而不写出四个单独的转换语句。
-
我找到了答案;谢谢你的帮助!