0:00

Consider the following incomplete method, which is intended to return the number of integers that evenly divide the integer inputVal. Assume that inputVal is greater than 0.

public static int numDivisors(int inputVal)
{
    int count = 0;
    for (int k = 1; k <=inputVal; k++)
    {
        if ( /* condition */ )
        {
            count++;
        }
    }
    return count;
}

Which of the following can be used to replace /* condition */ so that numDivisors will work as intended?

整除的定义是余数为零。考点一个是Java中整数算术的取模运算符(modulus operator)%。一个是Java的==表示在逻辑上判断左右两侧是否相等,与赋值区分开来。
1

Consider the following code segment.

for (int r = 3; r > 0; r--)
{
    int c;

    for (c = 1; c < r; c++)
    {
        System.out.print("-");
    }
    for (c = r; c <= 3; c++)
    {
        System.out.print("*");
    }
    System.out.println();
}

What is printed as a result of executing the code segment?

注意r是由3递减到1,第一行c可以取1或2,有两个-,以此类推。
1

Consider the following two classes.

public class A
{
    public void show()
    {
        System.out.print("A");
    }
}
public class B extends A
{
    public void show()
    {
        System.out.print("B");
    }
}

What is printed as a result of executing the following code segment?

A obj = new B();
obj.show();
考察继承中对于parent class method的重写(override)。注意将child object赋给parent type是子类型多态(subtype polymorphism),在对不同类型但有共同parent class的child object进行批量操作时非常管用。
2

Consider the following instance variable and method.

private int[] arr;

/** Precondition: arr.length > 0
 *  @return the largest value in array arr
 */
public int findMax()
{
    int maxVal = 0;

    for (int val : arr)
    {
        if (val > maxVal)
        {
            maxVal = val;
        }
    }

    return maxVal;
}

Method findMax is intended to return the largest value in the array arr. Which of the following best describes the conditions under which the method findMax will not work as intended?

使用for-each的求最大值算法本身没有问题。但是对最大值变量初始化为0有误,造成无法找到负值最大值。正确的做法应该是赋给数组的第一个元素(或任一元素)。
3

Assume that x and y are boolean variables and have been properly initialized.

(x || y) && x

Which of the following always evaluates to the same value as the expression above?

证明布尔代数的吸收率。
(x || y) && x等价于(x || y) && (x || 0)等价于x || (y && 0)等价于x || 0等价于x
当然考场上比较有效率的方法还是用真值表列出xy所有可能的组合。
1

Consider the following method, which is intended to return true if at least one of the three strings s1, s2, or s3 contains the substring art. Otherwise, the method should return false.

public static boolean containsArt(String s1, String s2, String s3)
{
    String all = s1 + s2 + s3;

    return (all.indexOf("art") != -1);
}

Which of the following method calls demonstrates that the method does not work as intended?

"similiar"的ar和"today"的t组合成了art。
1

Consider the following code segment.

for (int outer = 1; outer <= 6; outer ++)
{
    for (int inner = outer; inner <=6; inner ++)
    {
        if (inner % 2 ==0)
        {
            System.out.print(inner + " ");
        }
    }
    System.out.println();
}

What will be printed as a result of executing the code segment?

outer16共有6行,每行inner则从outer6,列数分别是3、3、2、2、1、1。
3

Consider the following method.

public static int[] operation(int[][] matrix, int r, int c)
{
    int[] result = new int[matrix.length];

    for (int j = 0; j < matrix.length; j++)
    {
        result[j] = matrix[r][j] * matrix[j][c];
    }
    return result;
}

The following code segment appears in another method in the same class.

int[][] mat = {{3, 2, 1, 4},
                {1, 2, 3, 4},
                {2, 2, 1, 3},
                {1, 1, 1, 1}};

int[] arr = operation(mat, 1, 2);

Which of the following represents the contents of arr as a result of executing the code segment?

算法上看是矩阵第2行的元素(1, 2, 3, 4)和第3列元素(1, 3, 1, 1)依次相乘。
2

A pair of number cubes is used in a game of chance. Each number cube has six sides, numbered from 1 to 6, inclusive, and there is an equal probability for each of the numbers to appear on the top side (indicating the cube’s value) when the number cube is rolled. The following incomplete statement appears in a program that computes the sum of the values produced by rolling two number cubes.

int sum = /* missing code */;

Which of the following replacements for /* missing code */ would best simulate the value produced as a result of rolling two number cubes?

(int) (Math.random() * 6)是0到5的随机数,模拟掷两个骰子的话需要两个相加(因为每次Math.random()是独立的,因而并不能合并)并加上2。
5

Consider the following interface and class declarations.

public interface Student
{ /* implementation not shown */ }

public class Athlete
{ /* implementation not shown */ }

public class TennisPlayer extends Athlete implements Student
{ /* implementation not shown */ }

Assume that each class has a zero-parameter constructor. Which of the following is not a valid declaration?

interface Studentclass Athlete本身没有任何关系。
4

Consider the following method.

public static boolean mystery(String str)
{
    String temp = "";

    for (int k = str.length(); k > 0; k--)
    {
        temp = temp + str.substring(k - 1, k);
    }

    return temp.equals(str);
}

Which of the following calls to mystery will return true?

算法生成的是一个和参数字符串逆序的字符串,最后判断是否相等事实上是确认参数是否为回文(palindrome),即正序和逆序对称。
5

Assume that x and y are boolean variables and have been properly initialized.

(x && y) && !(x || y)

Which of the following best describes the result of evaluating the expression above?

x && ytrue!(x || y)必为false,反之亦然。
2

Consider the following instance variable and method.

private int[] numbers;

public void mystery(int x)
{
    for (int k = 1; k < numbers.length; k = k + x)
    {
        numbers[k] = numbers[k - 1] + x;
    }
}

Assume that numbers has been initialized with the following values.

{17, 34, 21, 42, 15, 69, 48, 25, 39}

Which of the following represents the order of the values in numbers as a result of the call mystery(3)?

算法对数组第2个、第5个和第8个元素作用,把前一个元素加3赋给它们。
1

Consider the following method, biggest, which is intended to return the greatest of three integers. It does not always work as intended.

public static int biggest(int a, int b, int c)
{
    if ((a > b) && (a > c))
    {
        return a;
    }
    else if ((b > a) && (b > c))
    {
        return b;
    }
    else
    {
        return c;
    }
}

Which of the following best describes the error in the method?

ab相等时必返回c
3

Consider the following method.

public static void showMe(int arg)
{
    if (arg < 10)
    {
        showMe(arg+1);
    }
    else
    {
        System.out.print(arg + " ");
    }
}

What will be printed as a result of the call showMe(0)?

最后递归执行的showMe(10)显示10,其他均不显示。
1

Consider the following method.

/** Precondition: values has at least one row */
public static int calculate(int [][] values)
{
    int found =  values[0][0];
    int result = 0;
    for (int[] row : values)
    {
        for (int y = 0; y < row.length; y++)
        {
            if (row[y] > found)
            {
                found = row[y];
                result = y;
            }
        }
    }
    return result;
}

Which of the following best describes what is returned by the calculate method?

yrow[]的index,指示的是最大值所在的列。
5

Consider the following method.

/** Precondition: num > 0 */
public static int doWhat(int num)
{
    int var = 0;

    for (int loop = 1; loop <= num; loop = loop + 2)
    {
        var += loop;
    }
    return var;
}

Which of the following best describes the value returned from a call to doWhat?

1开始,间隔2的话都会是奇数。
4

What is printed as a result of executing the following statement?

System.out.println(404 / 10 * 10 + 1);

对于整数除法,404 / 1040
4

Consider the following code segment.

int x = 1;
while ( /* condition */ )
{
    if (x% 2 ==0)
    {
        System.out.print(x + " ");
    }
    x = x + 2;
}

The following conditions have been proposed to replace /* condition /* in the code segment.

I. x<0
II. x<=1
III. x<10

For which of the conditions will nothing be printed?

I不会执行循环,而II和III因为x一直是奇数,不会有任何输出。
5

Consider the following method.

/** Precondition: arr.length > 0 */
public static int mystery(int[] arr)
{
    int index = 0;
    int count = 0;
    int m = -1;

    for (int outer = 0; outer < arr.length; outer++)
    {
        count = 0;
        for (int inner = outer + 1; inner < arr.length; inner++)
        {
           if (arr[outer] == arr[inner])
            {
                count++;
            }
        }

        if (count > m)
        {
            index = outer;
            m = count;
        }
    }

    return index;
}

Assume that nums has been declared and initialized as an array of integer values. Which of the following best describes the value returned by the call mystery(nums)?

首先返回的是index,所有的value和count都可以排除。算法中每次给返回的index赋值时,记录重复元素的count都是本轮循环的最大值,因而返回的是重复次数最多元素也即最常出现元素的index。
5

Consider the following recursive method.

public static void whatsItDo(String str)
{
    int len = str.length();
    if (len > 1)
    {
        String temp = str.substring(0, len - 1);
        System.out.println(temp);
        whatsItDo(temp);
    }
}

What is printed as a result of the call whatsItDo("WATCH")?

考察substring()的用法,注意输出在调用递归之前。
4

Consider the following definition.

int[][] numbers = {{1, 2, 3},
                    {4, 5, 6}};

Which of the following code segments produces the output 123456?

考察for-each的用法,注意最后两个选项一个是index范围不对,一个是循环的次序不对。
1

Consider the following code segment from an insertion sort program.

for (int j = 1; j =0 && insertItem < arr[k])
    {
        arr[k+1] = arr[k];
        k--;
    }

    arr[k + 1] = insertItem;

    /* end of for loop */
}

Assume that array arr has been defined and initialized with the values {5, 4, 3, 2, 1}. What are the values in array arr after two passes of the for loop(i.e., when j = 2 at the point indicated by /* end of for loop */)?

j从左到右,而k从右到左。
3

Consider the following class.

public class SomeMethods
{
    public void one(int first)
    { /* implementation not shown */ }

    public void one(int first, int second)
    { /* implementation not shown */ }

    public void one(int first, String second)
    { /* implementation not shown */ }
}

Which of the following methods can be added to the SomeMethods class without causing a compile-time error?

I. public void one(int value)
II. public void one(String first, int second)
III. public void one(int first, int second, int thrid)

虽然I改了参数名字,但是方法签名还是和类里面第一个定义一致。II参数顺序不同,而III参数数目不同,这两个都是合法的重载。
4

Consider the following code segment.

int count = 0;

for (int x = 0; x < 4; x++)
{
    for (int y = x; y < 4; y++)
    {
        count++;
    }
}
System.out.println(count);

What is printed as a result of executing the code segment.

4+3+2+1。
3

Consider the following two methods, which appear within a single class.

public static void changeIt(int[] arr, int val, String word)
{
    arr = new int[5];
    val = 0;
    word = word.substring(0, 5);

    for (int k = 0; k < arr.length; k++)
    {
        arr[k] = 0;
    }
}

public static void start()
{
    int[] nums = {1, 2, 3, 4, 5};
    int value = 6;
    String name = "blackboard";

    changeIt(nums, value, name);

    for (int k = 0; k < nums.length; k++)
    {
        System.out.print(nums[k]+ " ");
    }

    System.out.print(value + " ");
    System.out.print(name);
}

What is printed as a result of the call start()?

如果changeIt中的arr没有分配新空间,原先的nums确实会被覆盖。基本数据类型和字符串则本来就不受影响。
5

Consider the following sort method. This method correctly sorts the elements of array data into increasing order.

public static void sort(int[] data)
{
    for ( int j = 0; j < data.length - 1; j++)
    {
        int m = j;
        for (int k = j + 1; k < data.length; k++)
        {
            if (data[k] < data [m])        /* Compare values */
            {
                m = k;
            }
        }
        int temp = data[m];            /* Assign to temp */
        data[m] = data[j];
        data[j] = temp;

        /* End of outer loop */
    }
}

Assume that sort is called with the array {6 ,3, 2, 5, 4, 1}. What will the value of data be after three passes of the outer loop (i.e., when j = 2 at the point indicated by /* End of outer loop */)?

第一轮1与6交换,第二轮2与3交换,第三轮不动。
2

Assume that sort is called with the array {1, 2, 3, 4, 5, 6}. How many times will the expression indicated by /* Compare value */ and the statement indicated by /* Assign to temp */ execute?

比较执行的次数是5+4+3+2+1,赋值因为j只到data.length-2因而只执行5次。
2

Consider the following recursive method.

/** Precondition: num>=0 */
public static int what(int num)
{
    if (num > 10)
    {
        return 1;
    }    
    else
    {
        return 1 + what(num / 10);
    }
}

Assume that int val has been declared and initialized with a value that satisfies the precondition of the method. Which of the following best describes the value returned by the call what(val)?

在递归的过程中,十进制数的每一位加一,注意并没有实际求出数字反映到结果中。
1

The price per box of ink pens advertised in an office supply catalog is based on the number of boxes ordered. The following table shows the pricing.

Number of Boxes Price per Box
1 up to but not including 5 $5.00
5 up to but not including 10 $3.00
10 or more $1.50

The following incomplete method is intended to return the total cost of an order based on the value of the parameter numBoxes.

/** Precondition: numBoxes>0 */
public static double getCost(int numBoxes)
{
    double totalCost = 0.0;

    /* missing code */

    return totalCost;
}

Which of the following code segments can be used to replace /* missing code */ so that method getCost will work as intended?

I.

if (numBoxes >= 10)
{
    totalCost = numBoxes * 1.50;
}
if (numBoxes >= 5)
{
    totalCost = numBoxes * 3.00;
}
if (numBoxes > 0)
{
    totalCost = numBoxes * 5.00;
}

II.

if (numBoxes >= 10)
{
    totalCost = numBoxes * 1.50;
}
else if (numBoxes >= 5)
{
    totalCost = numBoxes * 3.00;
}
else
{
    totalCost = numBoxes * 5.00;
}

III.

if (numBoxes > 0)
{
    totalCost = numBoxes * 5.00;
}
else if (numBoxes >= 5)
{
    totalCost = numBoxes * 3.00;
}
else if (numBoxes >= 10)
{
    totalCost = numBoxes * 1.50;
}
I对于同时满足前后条件的参数,后面会把前面的总价覆盖。III只会执行到第一个条件就结束了。
2

Consider the following code segment.

String[][] board = new String[5][5];
for (int row = 0; raw < 5; row++)
{
    for (int col = 0; col < 5; col++)
    {
        board[row][col] = "O";
    }
}

for (int val = 0; val < 5; val++)
{
    if (val % 2 == 1)
    {
        int row = val;
        int col = 0;
        while (col < 5 && row >= 0)
        {
            board[row][col] = "X";
            col++;
            row--;
        }
    }
}

Which of the following represents board after this code segment is executed?

val的可能取值为13colrow的循环往左下方画出了斜线。
5

Consider the following class declaration.

public class StudentInfo
{
    private String major;
    private int age;

    public String getMajor()
    {    return major;    }

    public String getAge()
    {    return age;    }

    // There may be instance variables, constructors, and methods that are not shown.
}

The following instance variable and method appear in another class.

private List students;

/** @return the average age of students with the given major;
 *                 -1.0 if no such students exist
 */
public double averageAgeinMajor(String theMajor)
{
    double sum = 0.0;
    int count = 0;
    for (StudentInfo k : students)
    {
        /* missing code */
    }

    if (count > 0)
    {
        return sum / count;
    }
    else
    {
        return -1.0;
    }
}

Which of the following could be used to replace /* missing code */ so that averageAgeInMajor will compile without error?

privatemajorage只能通过get method来访问。
2

Which of the following statements regarding interfaces is FALSE?

interface不能被实例化也没有实例变量。
3

Consider the problem of finding the maximum value in an array of integers. The following code segments are proposed solutions to the problem. Assume that the variable arr has been defined as an array of int values and has been initialized with one or more values.

I.

int max = Integer.MIN_VALUE;
for (int value : arr)
{
    if (max < value)
    {
        max = value;
    }
}

II.

int max = 0;
boolean first = true;
for (int value : arr)
{
    if (first)
    {
        max = value;
        first = false;
    }
    else if (max < value)
    {
        max = value;
    }
}

III.

int max = arr[0];
for (int k = 1; k <  arr.length; k++)
{
    if (max < arr[k])
    {
        max = arr[k];
    }
}

Which of the code segments will always correctly assign the maximum element of the array to the variable max?

初始化为整数最小值或数组任一元素都是对的。
5

Consider the following instance variable and method. Method wordsWithCommas is intended to return a string containing all the words in listOfWords contains ["one", "two", "three"], the string returned by the call wordsWithCommas() should be "{one, two, three}".

private List listOfWords;

public String wordsWithCommas()
{
    String result = "{";

    int sizeOfList = /* expression */;

    for (int k=0; k <  sizeOfList; k++)
    {
        result = result + listOfWords.get(k);

        if ( /* condition */ )
        {
            result = result + ", ";
        }
    }

    result = result + "}";
    return result;
}

Which of the following can be used to replace /* expression */ and /* condition */ so that wordsWithCommas will work as intended?

对数组和列表的循环都是小于length。对于这题判断最后一位不加逗号的判据则是length-1。
4

Consider the following binarySearch method. The method correctly performs a binary search.

/** Precondition: data is sorted in increasing order. */
public static int binarySearch(int[] data, int target)
{
    int start = 0;
    int end = data.length - 1;
    while (start <= end)
    {
        int mid = (start + end) / 2;
        if (target  data[mid])
        {
            start = mid + 1;
        }
        else
        {
            return mid;
        }
    }
    return -1;
}

Consider the following code segment.

int[] values = {1, 2, 3, 4, 5, 8, 8, 8};
int target = 8;

What value is returned by the call binarySearch(values, target)?

mid依次为35。注意整数除法会全部舍去小数位。
3

Suppose the binarySearch method is called with an array containing 2,000 elements sorted in increasing order. What is the maximum number of times that the statement indicated by /* Calculated midpoint */ could execute?

2的10次方是1024,11次方即能超过2,000。
4

Consider the following incomplete method that is intended to return a string formed by concatenating elements from the parameter words. The elements to be concatenated start with startIndex and continue through the last element of words and should appear in reverse order in the resulting string.

/** Precondition: words. length > 0;
 *        startIndex >= 0
 */
public static String concatWords(String[] words, int startIndex)
{
    String result = "";

    /* missing code */

    return result;
}

For example, the following code segment uses a call to the concatWords method.

String[] things = {"Bear, "Apple", "Gorilla", "House", "Car"};
System.out.println(concatWords(things, 2));

When the code segment is executed, the string "CarHouseGorilla" is printed.

The following three code segments have been proposed as replacements for /* missing code */.

I.

for (int k = startIndex; k < words.length; k++)
{
    result += words[k] + words[words.length - k - 1];
}

II.

int k = words.length - 1;
while (k >= startIndex)
{
    result += words[k];
    k--;
}

III.

String[] temp = new String[words.length];
for (int k = 0; k <= words.length / 2; k++)
{
    temp[k] = words[words.length - k - 1];
    temp[words.length - k - 1] = words[k];
}

for (int k = 0; k <  temp.length - startIndex; k++)
{
    result += temp[k];
}

Which of these code segments can be used to replace /* missing code */ so that concatWords will work as intended?

II从数组结尾开始循环,III从开头循环但已经颠倒了数组。
5

Consider the following method.

/** Precondition: 0 < numVals <= nums.length */
public static int mystery(int[] nums, int v, int numVals)
{
    int k = 0;

    if (v == nums[numVals - 1])
    {
        k = 1;
    }

    if (numVals == 1)
    {
        return k;
    }
    else
    {
        return k + mystery(nums, v, numVals - 1);
    }
}

Which of the following best describes what the call mystery(numbers, val, number.length) does? You may assume that variables numbers and val have been declared and initialized.

从数组最后一个元素开始,算法一一比较,相等则记1,最后再通过递归的方式求和。
3

Consider the following code segment.

List students = new ArrayList();

students.add("Alex");
students.add("Bob");
students.add("Carl");

for (int k = 0; k < students.size(); k++)
{
    System.out.print(students.set(k, "Alex") + " ");
}

System.out.println();

for (String str : students)
{
    System.out.print(str + " ");
}

What is printed as a result of executing the code segment?

对于List.set(),返回值是被替换掉的元素。因此第一遍输出是原始列表,第二遍输出是元素更新后的列表。
3


陈 欣

AADPS创始人

发表评论