【问题标题】:Loop confusion in a for loop, with a initial value of zero & it's conditionsfor循环中的循环混淆,初始值为零及其条件
【发布时间】:2013-05-05 20:14:44
【问题描述】:

在这个程序中,我对 for 循环如何在 List 类中的 InsertItem() 方法中执行感到困惑。

public class List {
    int[] a;
    int lastItem;
    public List() {
        a = new int[10];
        lastItem = -1;
    }
    public void InsertItem(int newItem, int location) {
        int i;
        for (i = lastItem; i >= location; i--) {
            a[i + 1] = a[i];
        }
        a[location] = newItem;
        lastItem++;
    }

我的困惑:lastItem 在 InsertItem 方法的 for 循环中初始化为 -1。假设位置为1,如果i小于0,循环将如何执行!

我正在为这个问题而烦恼。

【问题讨论】:

  • 你给InsertItem(int newItem, int location)传递了什么?
  • @NoobUnChained 什么都没通过,我只是想知道循环是如何工作的
  • 循环不需要工作,它取决于实例变量lastItem和参数location的当前值。添加每个项目后,您将其递增1。lastitem当您创建 List 类的实例以访问其实例方法 InsertItem(int newItem, int location) 时,将初始化为 -1
  • 是的,所以i的第一个值为-1,那么a[0] = a[0]?天哪,我很困惑。
  • 如果lastItem=-1location=0,它不会进入循环本身,看循环条件,i>=location-1>=0 不是,所以你怎么期望要执行的循环内的行!!!

标签: java for-loop conditional-statements


【解决方案1】:

只有在用户为变量location 输入的值小于或等于-1 时,for 循环才会执行。

但是将负值分配给location 将导致a[location] = newItem;a[i + 1] = a[i]; 出现错误,因为您将超出数组a[] 的边界。

如果您的目标是用值填充数组,则函数循环逻辑被破坏。

我建议将循环反转为递增而不是递减,并将lastItem 初始化为0,这样您就可以使此代码有效且没有错误。

【讨论】:

    猜你喜欢
    • 2016-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-12
    • 2018-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多