【问题标题】:About exercise 1.2.9 on p.115 in "Algorithms 4th Edition" by Robert Sedgewick and Kevin Wayne关于 Robert Sedgewick 和 Kevin Wayne 在“算法第 4 版”中第 115 页的练习 1.2.9
【发布时间】:2020-06-06 13:31:45
【问题描述】:

我正在阅读 Robert Sedgewick 和 Kevin Wayne 的“算法第 4 版”。

以下代码是我对第 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?
    }

}

【问题讨论】:

  • “不打印”是什么意思?
  • @Kayaman 对不起,我的英语很差。我的意思是“StdOut.println(c);”不打印 c 的值。
  • 那它打印什么?
  • @Kayaman 它什么也不打印。我猜这个代码在 StdIn.isEmpty() == true 时终止。

标签: java algorithm binary-search redirectstandardoutput


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-10
    • 2016-06-29
    • 1970-01-01
    • 2018-06-06
    • 2021-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多