gpt4 book ai didi

java - 查找数组中连续数字之间的差异

转载 作者:行者123 更新时间:2023-11-30 05:04:03 24 4
gpt4 key购买 nike

我需要以下输出例如:

int数组[] = {1,2,3,4,5};

应该使用for循环来完成

输出应采用以下形式:

List      Difference
1 0
2 1
3 1
4 1
5 1

这是我正在使用的代码,它在 4 之前工作正常,但在 5 时它显示越界,因为它查看数组中不存在的位置 5。所以,我需要帮助!!!

代码:

for (int counter = 0; counter < degreedays.length;++counter){
System.out.println("\t" + degreedays[counter] + "\t\t\t" + (degreedays[counter+1] - degreedays[counter]));

最佳答案

问题是您的代码使用规范的 for 循环循环遍历数组的所有索引,这很好;但是,循环体不仅使用索引 (counter),还使用索引加一 (counter+1),这超出了索引的范围数组!

更正您的代码,以便它不会尝试访问越界的数组元素,例如在尝试使用“counter+1”之前检查它是否是有效索引。

关于java - 查找数组中连续数字之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5711070/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com