1. 导入algs4.jar包
网址下载好algs4.jar,并在eclipse创建项目以后,右键项目名称
选择最下面的Properties,在弹出的窗口左侧选择Java Build Path,然后在右侧上方的四个横条中选择Libraries,如图:
选中Modulepath,再选择右侧按钮的Add External JARs…,找到并选中下载好的algs4.jar,点击右下角的open
open后,Modulepath下会出现algs4.jar,这时再选择右下角的Apply and Close
主界面的Referenced Libraries里出现了algs4.jar,表示导入外部库成功
需要使用外部库的话直接import edu.princeton.cs.algs4.*;
即可
我这里只导入了algs4.jar,没有导入stdlib.jar,因为我一旦以相同方式导入就会报错,然后一个库都没了,项目还不能使用,而且algs4里面包含了stdlib里面的输入输出函数等,应该是够用了的。
2. eclipse中重定向与管道
书中配套的网站提供了很多测试的txt文件,比如第一章1.5节的tinyUF.txt。书中是使用Dr java,直接用命令行重定向标准输入使得StdIn从文件而不是从终端应用程序中读取数据。
eclipse中的具体做法是:
右侧选中上面那张图中的想运行的.java文件,在上面的Run中选中Run Configurations
选择common选项卡,勾选底下的Input File,选择相应的要输入的文件,比如tinyUF.txt,如下图
然后在(x)=Arguments的Program argument中输入tinyUF.txt,就可以点击右下角的Run了
主函数的代码:
public static void main(String[] args)
{
int N = StdIn.readInt();
WeightedQuickUnionUF uf = new WeightedQuickUnionUF(N);
while (!StdIn.isEmpty())
{
int p = StdIn.readInt();
int q = StdIn.readInt();
if(uf.connected(p, q)) continue;
uf.union(p, q);
StdOut.println(p + " " + q);
}
StdOut.println(uf.count() + "components");
}
运行的时候发现,程序无法自己终止,而且始终输出不了最后有多少个连通分量:
原因是程序一直卡在上面的while循环中,它没有收到结束标志,所以一直在等待继续输入中,解决办法是输入ctrl+d(不是Command,有的终端可能是输入ctrl+z),输入后,程序结束,输出有两个分量
3. 泛型
书中大量使用泛型来构建可以处理任意对象的数据结构,而且它的主要用法是用尖括号和关键字Item,我按书中的代码敲入eclipse中发现报错,原来是不能用书上的写法写泛型。
没有错误可以运行的写法如下,是第一章1.3节中的背包:
package chap1_fundamental;
import java.util.*;
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
public class Bag<T> implements Iterable<T>
{
private Node first;
private class Node
{
T item;
Node next;
}
public void add(T item)
{
Node oldfirst = first;
first = new Node();
first.item = item;
first.next = oldfirst;
}
public int size()
{
Node cur = first;
int count = 0;
while(cur != null)
{
count += 1;
cur = cur.next;
}
return count;
}
public Iterator<T> iterator()
{ return new ListIterator(); }
private class ListIterator implements Iterator<T>
{
private Node current = first;
public boolean hasNext()
{ return current != null; }
public void remove() { }
public T next()
{
T item = current.item;
current = current.next;
return item;
}
}
public static void main(String[] args)
{
Bag<Double> numbers = new Bag<Double>();
System.out.println("please enter some numbers: ");
while (!StdIn.isEmpty())
numbers.add(StdIn.readDouble());
int N = numbers.size();
double sum = 0.0;
for (double x: numbers)
sum += x;
double mean = sum/N;
sum = 0.0;
for (double x: numbers)
sum += (x-mean)*(x-mean);
double std = Math.sqrt(sum/(N-1));
StdOut.printf("Mean: %.2f\n", mean);
StdOut.printf("Std dev: %.2f\n", std);
}
}
运行之后需要在控制台输入想要求平均值的数,然后按ctrl+d即可。