1、 安裝JAVA
JAVA網址:http://www.oracle.com/technetwork/java/javase/downloads/index.html
配置環境變量(我把JAVA安裝在路徑:F:\Java\jdk1.8):
PATH=.;%JAVA_HOME%\bin
CLASSPATH=.;%JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\lib\toos.jar;
JAVA_HOME=F:\Java\jdk1.8
檢查JAVA是否安裝成功(出現如下的信息則表示JAVA安裝完成):
2、 下載相關文件
打開普林斯頓大學網站:http://algs4.cs.princeton.edu/code/
分別點擊下載兩個文件(algs4.jar和algs4-data.zip)
重點:(我當時因為沒有按要求配置該文件,導致運行所有的官網下載的程序都失敗,統一提示為:錯誤: 找不到或無法加載主類)
在該頁面的下面可以找到如下這段話:
說明了要把下載的algs4.jar文件存放到如下文件夾:C:\Users\Kylin Lin\algs4(注意:將Kylin Lin換成你的用戶名),然后將該文件的路徑添加到剛才的JAVA環境變量classpath中,所以完整的classpath路徑應該是這樣的:
.;%JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\lib\toos.jar;C:\Users\Kylin Lin\algs4\algs4.jar;
3、 配置Eclipse
Eclipse下載地址:http://www.eclipse.org/downloads/
安裝時選擇第一個選項即可
安裝完畢后新建JAVA工程(我這里命名為Algorithms),添加剛才下載的algs4.jar文件,否則不能使用書中代碼的自定義庫
至此,開發環境配置完畢,為了方便,把下載的另一個文件algs4-data.zip解壓到該工程的src文件夾中
4、 測試
在該工程中新建類BinarySearch
package chapter1; /****************************************************************************** * Compilation: javac chapter1\BinarySearch.java * Execution: java chapter1.BinarySearch tinyW.txt < tinyT.txt * Data files: http://www.cs.princeton.edu/introcs/43sort/emails.txt * http://www.cs.princeton.edu/introcs/43sort/whitelist.txt * * Read in an alphabetical list of words from the given file. * Then prompt the user to enter words. The program reports which * words are *not* in the wordlist. * * % java BinarySearch whitelist.txt < emails.html * marvin@spam * mallory@spam * eve@airport * ******************************************************************************/ import java.util.Arrays; import edu.princeton.cs.algs4.In; import edu.princeton.cs.algs4.StdIn; import edu.princeton.cs.algs4.StdOut; public class BinarySearch { // return the index of the key in the sorted array a[]; -1 if not found public static int search(String key, String[] a) { return search(key, a, 0, a.length); } public static int search(String key, String[] a, int lo, int hi) { // possible key indices in [lo, hi) if (hi <= lo) return -1; int mid = lo + (hi - lo) / 2; int cmp = a[mid].compareTo(key); if (cmp > 0) return search(key, a, lo, mid); else if (cmp < 0) return search(key, a, mid+1, hi); else return mid; } // whitelist, exception filter public static void main(String[] args) { In in = new In(args[0]); String s = in.readAll(); String[] words = s.split("\\s+"); System.err.println("Done reading words"); // sort the words (if needed) Arrays.sort(words); System.err.println("Done sorting words"); // prompt user to enter a word and check if it's there while (!StdIn.isEmpty()) { String key = StdIn.readString(); if (search(key, words) < 0) StdOut.println(key); } } } |
得到如下的顯示,則表示配置成功,可以運行官方的源程序以及使用官方所自定義的庫
細節提示:
1. 當前的運行目錄是Algorithms\src,且該目錄下需要具有tinyW.txt和tinyT.txt文件
2. 因為我把algs4-data.zip文件解壓到了src目錄下,所以需要用包來管理源程序,否則會造成混亂,所以在用java命令運行時需要指定包名(在源程序中指定了包名: package chapter1;)
參考我的工程結構
5、 在Eclipse中配置github
參考:http://www.cnblogs.com/yc-755909659/p/3753626.html