【发布时间】: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=-1和location=0,它不会进入循环本身,看循环条件,i>=location,-1>=0不是,所以你怎么期望要执行的循环内的行!!!
标签: java for-loop conditional-statements