关于 Robert Sedgewick 和 Kevin Wayne 在 "Algorithms 4th Edition" 中第 115 页的练习 1.2.9

About exercise 1.2.9 on p.115 in "Algorithms 4th Edition" by Robert Sedgewick and Kevin Wayne

我正在阅读 Robert Sedgewick 和 Kevin Wayne 的 "Algorithms 4th Edition"。

以下代码是我对第 115 页练习 1.2.9 的回答。

我希望此代码打印所有搜索期间检查的密钥总数,但此代码不打印计数器的值。

为什么?

package exercise.chapter2.section2;

import java.util.Arrays;

import edu.princeton.cs.algs4.Counter;
import edu.princeton.cs.algs4.In;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;

public class Ex1_2_09 {

    public static int indexOf(int[] a, int key, Counter c) {
        int lo = 0;
        int hi = a.length - 1;
        while (lo <= hi) {
            // Key is in a[lo..hi] or not present.
            c.increment();
            int mid = lo + (hi - lo) / 2;
            if      (key < a[mid]) hi = mid - 1;
            else if (key > a[mid]) lo = mid + 1;
            else return mid;
        }
        return -1;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        // read the integers from a file
        In in = new In(args[0]);
        int[] whitelist = in.readAllInts();

        // sort the array
        Arrays.sort(whitelist);

        Counter c = new Counter("- the total number of keys examinded during all searches");
        // read integer key from standard input; print if not in whitelist
        while (!StdIn.isEmpty()) {
            int key = StdIn.readInt();
            if (indexOf(whitelist, key, c) == -1) {
                StdOut.println(key);
            }
        }
        StdOut.println(c);  //I want to print c, but this code doesn't print it. Why?
    }

}

StdIn 永远不会为空。这是你的键盘,它只能等待你的输入。您需要添加一些东西来结束循环,例如用户输入一些特定的键,例如 q 或其他不会影响程序其余部分功能的键。