我正在阅读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
或其他不会影响程序其余部分功能的键。