算法4代码使用-IDEA

最近在看算法4的书,需要自己在IDEA中运行书上的示例,所以这篇文章来讲解如何去使用书上的代码以及怎么去跑这些代码。

一、下载algs4-data.zip和algs4.jar

1、在算法4的官网中下载这两个文件

 

 

 

2、下载完成后解压以及配置系统环境变量

将algs4-data.zip解压至你的项目中,src文件下。

 

我将algs4.jar文件放置这个目录下

 

 然后在IEDA中导入这个jar包以及在系统的环境变量中添加。

首先找到classpath,点击编辑。将E:\Java\algs\algs4.jar;添加进去

 

然后在IDEA中选择配置,将algs4.jar配置到项目中

 

 

 这样我们就算完成了配置。

二、运行代码测试

在这里我们随便选择一个代码测试,选择第三章的FrequencyCounter.java进行运行测试,将代码复制进去

import edu.princeton.cs.algs4.ST;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;

public class FrequencyCounter {
    // Do not instantiate.
    private FrequencyCounter() { }

    /**
     * Reads in a command-line integer and sequence of words from
     * standard input and prints out a word (whose length exceeds
     * the threshold) that occurs most frequently to standard output.
     * It also prints out the number of words whose length exceeds
     * the threshold and the number of distinct such words.
     *
     * @param args the command-line arguments
     */
    public static void main(String[] args) {
        int distinct = 0, words = 0;
        int minlen = Integer.parseInt(args[0]);
        ST<String, Integer> st = new ST<String, Integer>();

        // compute frequency counts
        while (!StdIn.isEmpty()) {
            String key = StdIn.readString();
            if (key.length() < minlen) continue;
            words++;
            if (st.contains(key)) {
                st.put(key, st.get(key) + 1);
            }
            else {
                st.put(key, 1);
                distinct++;
            }
        }

        // find a key with the highest frequency count
        String max = "";
        st.put(max, 0);
        for (String word : st.keys()) {
            if (st.get(word) > st.get(max))
                max = word;
        }

        StdOut.println(max + " " + st.get(max));
        StdOut.println("distinct = " + distinct);
        StdOut.println("words    = " + words);
    }

}

上面的导入包,使用alter + enter快捷键导入包,这样就写好了,下面进行跑代码环节:

 

 

根据书上的代码,在上面的位置分别写入

javac FrequencyCounter.java

java FrequencyCounter 1 < tinyTale.txt

 

 

 

 

 这样就将代码跑起来了。

 

posted @ 2021-01-16 14:05  wangheq  阅读(461)  评论(0编辑  收藏  举报