7.1 汉诺塔
public class MainClass {
public static void main(String[] args) {
int nDisks = 3;
doTowers(nDisks, 'A', 'B', 'C');
}
public static void doTowers(int topN, char from, char inter, char to) {
if (topN == 1){
System.out.println("Disk 1 from "
+ from + " to " + to);
}else {
doTowers(topN - 1, from, to, inter);
System.out.println("Disk "
+ topN + " from " + from + " to " + to);
doTowers(topN - 1, inter, from, to);
}
}
}
7.2 斐波那契数列
public class MainClass {
public static void main(String[] args) {
for (int counter = 0; counter <= 10; counter++){
System.out.printf("Fibonacci of %d is: %d\n", counter, fibonacci(counter));
}
}
public static long fibonacci(long number) {
if ((number == 0) || (number == 1))
return number;
else
return fibonacci(number - 1) + fibonacci(number - 2);
}
}
7.3 阶乘
public class MainClass {
public static void main(String args[]) {
for (int counter = 0; counter <= 10; counter++){
System.out.printf("%d! = %d\n", counter,
factorial(counter));
}
}
public static long factorial(long number) {
if (number <= 1)
return 1;
else
return number * factorial(number - 1);
}
}
7.4 标签
Java 中的标签是为循环设计的,是为了在多重循环中方便的使用 break 和coutinue 。
public class Main {
public static void main(String[] args) {
String strSearch = "This is the string in which you have to search for a substring.";
String substring = "substring";
boolean found = false;
int max = strSearch.length() - substring.length();
testlbl:
for (int i = 0; i <= max; i++) {
int length = substring.length();
int j = i;
int k = 0;
while (length-- != 0) {
if(strSearch.charAt(j++) != substring.charAt(k++)){
continue testlbl;
}
}
found = true;
break testlbl;
}
if (found) {
System.out.println("发现子字符串。");
}
else {
System.out.println("字符串中没有发现子字符串。");
}
}
}
7.5 finalize
Java 允许定义这样的方法,它在对象被垃圾收集器析构(回收)之前调用,这个方法叫做 finalize( ),它用来清除回收对象。
例如,你可以使用 finalize() 来确保一个对象打开的文件被关闭了。在 finalize() 方法里,你必须指定在对象销毁时候要执行的操作。
protected void finalize(){
// 在这里终结代码
}
/* 关键字 protected 是一个限定符,它确保 finalize() 方法不会被该类以外的代码调用。
当然,Java 的内存回收可以由 JVM 来自动完成。如果你手动使用,则可以使用上面的方法
*/