首页 > 解决方案 > 在 for 循环中更新后未保存变量值

问题描述

我正在尝试使用 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);

标签: javafor-loop

解决方案


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);
}

i是数组中值的副本,它不像指针,更新i只会更新副本,该副本在下一次循环迭代中被丢弃。


推荐阅读