java - 在 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);
解决方案
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
只会更新副本,该副本在下一次循环迭代中被丢弃。
推荐阅读
- git - 如何结合两个 git repos,保留两者的历史,以及一个的哈希?
- python - 每当我输入“import discord”时,我都会在 Python 3.6 上收到一条错误消息
- javascript - 如何在 php codeigniter 中从 CRUD ajax 添加数据?
- android - `onTrimMemory` 是否在 UI 线程上被调用?
- c# - C# 使用按钮更改表单的背景颜色
- php - woocommerce中类别和产品的相同基本网址
- postgresql - 如何将一个数据库中表的特定列传输到另一个数据库?
- javascript - 将 JsonResponse 数据格式化成表格
- c# - 多个 WindowsBase 程序集冲突
- postgresql - 最小的 PostgreSQL 数据文件集