1.打印输出10行杨辉三角形。杨辉三角形形式如下:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
…
其构成规律如下:
(1)第0列元素和主对角线元素均为1。
(2)其余元素为其左上方和正上方元素之和。
(3)每行数据的个数递增1。
代码如下。
packagec test;
public class YanHui {
public static void main(String[] args) {
int[][] Tarry = new int[10][10];
for (int i = 0; i < 10; i++) {
for (int j = 0; j <= i; j++) {
if (j > 0 && j < i) {
Tarry[i][j] = Tarry[i - 1][j - 1] + Tarry[i - 1][j];
} else {
Tarry[i][j] = 1;
}
System.out.print(Tarry[i][j] + ",");
}
System.out.println();
}
}
}
2.用HashMap来存储一些输入的公司名称和地址,然后使用Iterator遍历整个Map,输出存储的结果。程序代码如下:
/** MapEntrySetDemo.java @author ZDS
* 2007-2-19 下午21:49:20 */
package chap06;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/** 遍历HashMap的例子*/
public class MapEntrySetDemo {
public static void main(String[] argv) {
// Construct and load the hash. This simulates loading a
// database or reading from a file, or wherever the data is.
Map map = new HashMap();
// The hash maps from company name to address.
// In real life this might map to an Address object...
map.put("Adobe", "Mountain View, CA");
map.put("IBM", "White Plains, NY");
map.put("Learning Tree", "Los Angeles, CA");
map.put("Microsoft", "Redmond, WA");
map.put("Netscape", "Mountain View, CA");
map.put("O'Reilly", "Sebastopol, CA");
map.put("Sun", "Mountain View, CA");
// List the entries using entrySet()
Set entries = map.entrySet();
Iterator it = entries.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
System.out.println(entry.getKey() + "-->" + entry.getValue());
}
}
}