Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

java - Coding a loop inside of an Array in pseudocode

I'm new to computer science. I've been told there is only 1 bug in the following Java type pseudo-code but i'm unable to figure it out. Isn't there more then 1? First the if statement means it won't loop as size doesn't equal max size, but i think the loop is also incorrect as rather then i<=size shouldn't it be i<=maxsize?

private int size = 0;
private int maxsize = 16;
private int[] arr = new int[maxsize];

public void append(val, list)
{
    if (size == maxsize)
    {
        int[] newArr = new int[maxsize * 2];
        for (i = 0; i <= size ; i++)
            newArr[i] = arr[i];
        arr = newArr;
        maxsize = maxsize*2;
    }
    arr[size++] = val;
}

Out of these options, which one is correct?

  • Line 1 should read: private int size = 16;
  • Line 7 should read: if (size > maxsize)
  • Line 10 should read: for (i = 0 ; i <= maxsize ; i++)
  • Line 13 should come before line 10
  • Line 15 should read: arr[++size] = val;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There’s just an off-by-one error. The code is trying to copy size+1 elements from the old array into the new, but the old array only has size elements.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...