本篇文章给大家谈谈王颖奇20171010129《面向对象程序设计,以及java》第十一周学习总结的知识点,同时本文还将给你拓展20172308《程序设计与数据结构》第十一周学习总结、20175227张
本篇文章给大家谈谈王颖奇 20171010129《面向对象程序设计,以及java》第十一周学习总结的知识点,同时本文还将给你拓展20172308《程序设计与数据结构》第十一周学习总结、20175227 张雪莹 2018-2019-2 《Java 程序设计》第十一周学习总结、201771010101 白玛次仁《面向对象程序设计(Java)》第十一周学习总结、201771010112罗松《面向对象程序设计(java)》第十一周学习总结等相关知识,希望对各位有所帮助,不要忘了收藏本站喔。
本文目录一览:- 王颖奇 20171010129《面向对象程序设计(java)》第十一周学习总结(面向对象程序设计网课)
- 20172308《程序设计与数据结构》第十一周学习总结
- 20175227 张雪莹 2018-2019-2 《Java 程序设计》第十一周学习总结
- 201771010101 白玛次仁《面向对象程序设计(Java)》第十一周学习总结
- 201771010112罗松《面向对象程序设计(java)》第十一周学习总结
王颖奇 20171010129《面向对象程序设计(java)》第十一周学习总结(面向对象程序设计网课)
实验十一 集合
实验时间 2018-11-8
1、实验目的与要求
(1) 掌握 Vetor、Stack、Hashtable 三个类的用途及常用 API;
(2) 了解 java 集合框架体系组成;
(3) 掌握 ArrayList、LinkList 两个类的用途及常用 API。
(4) 了解 HashSet 类、TreeSet 类的用途及常用 API。
(5) 了解 HashMap、TreeMap 两个类的用途及常用 API;
(6) 结对编程(Pair programming)练习,体验程序开发中的两人合作。
2、实验内容和步骤
实验 1: 导入第 9 章示例程序,测试程序并进行代码注释。
测试程序 1:
l 使用 JDK 命令运行编辑、运行以下三个示例程序,结合运行结果理解程序;
l 掌握 Vetor、Stack、Hashtable 三个类的用途及常用 API。
// 示例程序 1 import java.util.Vector;
class Cat { private int catNumber;
Cat(int i) { catNumber = i; }
void print() { System.out.println("Cat #" + catNumber); } }
class Dog { private int dogNumber;
Dog(int i) { dogNumber = i; }
void print() { System.out.println("Dog #" + dogNumber); } }
public class CatsAndDogs { public static void main(String[] args) { Vector cats = new Vector(); for (int i = 0; i < 7; i++) cats.addElement(new Cat(i)); cats.addElement(new Dog(7)); for (int i = 0; i < cats.size(); i++) ((Cat) cats.elementAt(i)).print(); } } |
// 示例程序 2 import java.util.*;
public class Stacks { static String[] months = { "1", "2", "3", "4" };
public static void main(String[] args) { Stack stk = new Stack(); for (int i = 0; i < months.length; i++) stk.push(months[i]); System.out.println(stk); System.out.println("element 2=" + stk.elementAt(2)); while (!stk.empty()) System.out.println(stk.pop()); } } |
// 示例程序 3 import java.util.*;
class Counter { int i = 1;
public String toString() { return Integer.toString(i); } }
public class Statistics { public static void main(String[] args) { Hashtable ht = new Hashtable(); for (int i = 0; i < 10000; i++) { Integer r = new Integer((int) (Math.random() * 20)); if (ht.containsKey(r)) ((Counter) ht.get(r)).i++; else ht.put(r, new Counter()); } System.out.println(ht); } } |
示例程序 1:
因为 dog 类无法强制类型转换为 cat 类,所以程序会出现以下错误:
更改思路(两种方法):
(1)输出 cat 类时,将 dog 类放到 cat 类的输出循环之外,并将 Dog (7) 中的内容强制转换成 dog 类后单独输出。
更改后代码:


package demo;
import java.util.Vector;
class Cat {
private int catNumber;
Cat(int i) {
catNumber = i;
}
void print() {
System.out.println("Cat #" + catNumber);
}
}
class Dog {
private int dogNumber;
Dog(int i) {
dogNumber = i;
}
void print() {
System.out.println("Dog #" + dogNumber);
}
}
public class CatsAndDogs {
public static void main(String[] args) {
Vector cats = new Vector();
for (int i = 0; i < 7; i++)
cats.addElement(new Cat(i));
cats.addElement(new Dog(7));
for (int i = 0; i < 7; i++)
((Cat) cats.elementAt(i)).print();
((Dog) cats.elementAt(7)).print();
}
}
(2)输出结果时,使用 instanceof 语句对类(cat 和 dog 类)进行判断,根据情况输出。
更改后代码:


package demo;
import java.util.Vector;
class Cat {
private int catNumber;
Cat(int i) {
catNumber = i;
}
void print() {
System.out.println("Cat #" + catNumber);
}
}
class Dog {
private int dogNumber;
Dog(int i) {
dogNumber = i;
}
void print() {
System.out.println("Dog #" + dogNumber);
}
}
public class CatsAndDogs {
public static void main(String[] args) {
Vector cats = new Vector();
for (int i = 0; i < 7; i++)
cats.addElement(new Cat(i));
cats.addElement(new Dog(7));
for (int i = 0; i < cats.size(); i++)
if(cats.elementAt(i) instanceof Cat) {
((Cat) cats.elementAt(i)).print();
}
else
((Dog) cats.elementAt(i)).print();
}
}
更改后的结果(均为以下结果):
示例程序 2:
示例程序 3:
程序解析:
该示例检验 Math.random () 方法的随机性。在理想情况下,该方法应该产生一系列完美的随机分布的数字。为了验证这一点,需要生成数量众多的随机数字,然后计算落在不同范围内的数字量。该程序生成 10000 个随数,查看它们在 0~20 之间的分布如何。


package demo;
import java.util.*;
class Counter {
int i = 1;
//default:即不加任何访问修饰符,通常称为“默认访问模式“。该模式下,只允许在同一个包中进行访问。
public String toString() {
return Integer.toString(i);
}
}
public class Statistics {
public static void main(String[] args) {
Hashtable ht = new Hashtable();
for (int i = 0; i < 10000; i++) {
Integer r = new Integer((int) (Math.random() * 20));
//用Math.random()方法生成0到19的所有整数,并以int型存放,同时用Integer方法封装到数组中
if (ht.containsKey(r))
((Counter) ht.get(r)).i++;
else
ht.put(r, new Counter());
//输出r中数据的键值对出现的次数
}
System.out.println(ht);
}
}
运行结果:
关于 int i 为何种访问权限修饰符的思考(上课所提到的):
测试程序 2:
l 使用 JDK 命令编辑运行 ArrayListDemo 和 LinkedListDemo 两个程序,结合程序运行结果理解程序;
import java.util.*;
public class ArrayListDemo { public static void main(String[] argv) { ArrayList al = new ArrayList(); // Add lots of elements to the ArrayList... al.add(new Integer(11)); al.add(new Integer(12)); al.add(new Integer(13)); al.add(new String("hello")); // First print them out using a for loop. System.out.println("Retrieving by index:"); for (int i = 0; i < al.size(); i++) { System.out.println("Element " + i + " = " + al.get(i)); } } } |
import java.util.*; public class LinkedListDemo { public static void main(String[] argv) { LinkedList l = new LinkedList(); l.add(new Object()); l.add("Hello"); l.add("zhangsan"); ListIterator li = l.listIterator(0); while (li.hasNext()) System.out.println(li.next()); if (l.indexOf("Hello") < 0) System.err.println("Lookup does not work"); else System.err.println("Lookup works"); } } |
l 在 Elipse 环境下编辑运行调试教材 360 页程序 9-1,结合程序运行结果理解程序;
l 掌握 ArrayList、LinkList 两个类的用途及常用 API。
ArrayListDemo(运行结果):
增加 System.out.println (al.size ()); 语句可以输出有多少个元素
LinkedListDemo(运行结果):
教材 p360 9-1 程序:


package linkedList;
import java.util.*;
/**
* This program demonstrates operations on linked lists.
* @version 1.11 2012-01-26
* @author Cay Horstmann
*/
public class LinkedListTest
{
public static void main(String[] args)
{
List<String> a = new LinkedList<>();
//生成一个String型数组a,用add方法追加元素
a.add("Amy");
a.add("Carl");
a.add("Erica");
List<String> b = new LinkedList<>();
//生成一个String型数组b,用add方法追加元素
b.add("Bob");
b.add("Doug");
b.add("Frances");
b.add("Gloria");
// merge the words from b into a
//将b数组中的单词合并到a中
ListIterator<String> aIter = a.listIterator();
Iterator<String> bIter = b.iterator();
while (bIter.hasNext())
{
if (aIter.hasNext()) aIter.next();
aIter.add(bIter.next());
}
System.out.println(a);
// remove every second word from b
//删除b数组中的第二个单词
bIter = b.iterator();
while (bIter.hasNext())
{
bIter.next(); // skip one element(跳过一个元素)
if (bIter.hasNext())
{
bIter.next(); // skip next element(跳过下一个元素)
bIter.remove(); // remove that element(移除那个元素)
}
}
System.out.println(b);
// bulk operation: remove all words in b from a
//批量操作:从a中删除b中的所有单词
a.removeAll(b);
System.out.println(a);
}
}
运行结果:
测试程序 3:
l 运行 SetDemo 程序,结合运行结果理解程序;
import java.util.*; public class SetDemo { public static void main(String[] argv) { HashSet h = new HashSet (); // 也可以 Set h=new HashSet () h.add("One"); h.add("Two"); h.add("One"); // DUPLICATE h.add("Three"); Iterator it = h.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } } |
运行结果:
l 在 Elipse 环境下调试教材 365 页程序 9-2,结合运行结果理解程序;了解 HashSet 类的用途及常用 API。


package set;
import java.util.*;
/**
* This program uses a set to print all unique words in System.in.
* @version 1.12 2015-06-21
* @author Cay Horstmann
*/
public class SetTest
{
public static void main(String[] args)
{
Set<String> words = new HashSet<>(); // HashSet implements Set
long totalTime = 0;
try (Scanner in = new Scanner(System.in))
{
while (in.hasNext())
{
String word = in.next();
long callTime = System.currentTimeMillis();
words.add(word);
callTime = System.currentTimeMillis() - callTime;
totalTime += callTime;
}
}
Iterator<String> iter = words.iterator();
for (int i = 1; i <= 20 && iter.hasNext(); i++)
System.out.println(iter.next());
System.out.println(". . .");
System.out.println(words.size() + " distinct words. " + totalTime + " milliseconds.");
}
}
l 在 Elipse 环境下调试教材 367 页 - 368 程序 9-3、9-4,结合程序运行结果理解程序;了解 TreeSet 类的用途及常用 API。


package treeSet;
import java.util.*;
/**
* This program sorts a set of item by comparing their descriptions.
* @version 1.12 2015-06-21
* @author Cay Horstmann
*/
public class TreeSetTest
{
public static void main(String[] args)
{
SortedSet<Item> parts = new TreeSet<>();
parts.add(new Item("Toaster", 1234));
parts.add(new Item("Widget", 4562));
parts.add(new Item("Modem", 9912));
System.out.println(parts);
NavigableSet<Item> sortByDescription = new TreeSet<>(
Comparator.comparing(Item::getDescription));
sortByDescription.addAll(parts);
System.out.println(sortByDescription);
}
}


package treeSet;
import java.util.*;
/**
* An item with a description and a part number.
*/
public class Item implements Comparable<Item>
{
private String description;
private int partNumber;
/**
* Constructs an item.
*
* @param aDescription
* the item''s description
* @param aPartNumber
* the item''s part number
*/
public Item(String aDescription, int aPartNumber)
{
description = aDescription;
partNumber = aPartNumber;
}
/**
* Gets the description of this item.
*
* @return the description
*/
public String getDescription()
{
return description;
}
public String toString()
{
return "[description=" + description + ", partNumber=" + partNumber + "]";
}
public boolean equals(Object otherObject)
{
if (this == otherObject) return true;
if (otherObject == null) return false;
if (getClass() != otherObject.getClass()) return false;
Item other = (Item) otherObject;
return Objects.equals(description, other.description) && partNumber == other.partNumber;
}
public int hashCode()
{
return Objects.hash(description, partNumber);
}
public int compareTo(Item other)
{
int diff = Integer.compare(partNumber, other.partNumber);
return diff != 0 ? diff : description.compareTo(other.description);
}
}
运行结果:
测试程序 4:
l 使用 JDK 命令运行 HashMapDemo 程序,结合程序运行结果理解程序;
import java.util.*; public class HashMapDemo { public static void main(String[] argv) { HashMap h = new HashMap(); // The hash maps from company name to address. h.put("Adobe", "Mountain View, CA"); h.put("IBM", "White Plains, NY"); h.put("Sun", "Mountain View, CA"); String queryString = "Adobe"; String resultString = (String)h.get(queryString); System.out.println("They are located in: " + resultString); } } |
运行结果:
l 在 Elipse 环境下调试教材 373 页程序 9-6,结合程序运行结果理解程序;
了解 HashMap、TreeMap 两个类的用途及常用 API。
代码:


package map;
import java.util.*;
/**
* This program demonstrates the use of a map with key type String and value type Employee.
* @version 1.12 2015-06-21
* @author Cay Horstmann
*/
public class MapTest
{
public static void main(String[] args)
{
Map<String, Employee> staff = new HashMap<>();
staff.put("144-25-5464", new Employee("Amy Lee"));
staff.put("567-24-2546", new Employee("Harry Hacker"));
staff.put("157-62-7935", new Employee("Gary Cooper"));
staff.put("456-62-5527", new Employee("Francesca Cruz"));
// print all entries
System.out.println(staff);
// remove an entry
staff.remove("567-24-2546");
// replace an entry
staff.put("456-62-5527", new Employee("Francesca Miller"));
// look up a value
System.out.println(staff.get("157-62-7935"));
// iterate through all entries
staff.forEach((k, v) ->
System.out.println("key=" + k + ", value=" + v));
}
}


package map;
/**
* A minimalist employee class for testing purposes.
*/
public class Employee
{
private String name;
private double salary;
/**
* Constructs an employee with $0 salary.
* @param n the employee name
*/
public Employee(String name)
{
this.name = name;
salary = 0;
}
public String toString()
{
return "[name=" + name + ", salary=" + salary + "]";
}
}
运行结果:
实验 2:结对编程练习:
l 关于结对编程:以下图片是一个结对编程场景:两位学习伙伴坐在一起,面对着同一台显示器,使用着同一键盘,同一个鼠标,他们一起思考问题,一起分析问题,一起编写程序
l 关于结对编程的阐述可参见以下链接:
http://www.cnblogs.com/xinz/archive/2011/08/07/2130332.html
http://en.wikipedia.org/wiki/Pair_programming
l 对于结对编程中代码设计规范的要求参考:
http://www.cnblogs.com/xinz/archive/2011/11/20/2255971.html
以下实验,就让我们来体验一下结对编程的魅力。
l 确定本次实验结对编程合作伙伴;
合作伙伴:王斌龙
l 各自运行合作伙伴实验九编程练习 1,结合使用体验对所运行程序提出完善建议;
王斌龙的代码:


package ba;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
public class Cardtest {
// 文件读取模块 利用ArrayList构造studentlist存放文件内容
private static ArrayList<Card> cardlist;
public static void main(String[] args) {
cardlist = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
File file = new File("C:\\身份证号.txt");
try {
// 创建文件字符流,分类读取文件内容
FileInputStream fis = new FileInputStream(file);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
String temp = null;
while ((temp = in.readLine()) != null) {
Scanner linescanner = new Scanner(temp);
linescanner.useDelimiter(" ");
String name = linescanner.next();
String id = linescanner.next();
String sex = linescanner.next();
String age = linescanner.next();
String area = linescanner.nextLine();
Card card = new Card();
card.setName(name);
card.setId(id);
card.setSex(sex);
int a = Integer.parseInt(age);
card.setAge(a);
card.setArea(area);
cardlist.add(card);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("信息文件找不到");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("信息文件读取错误");
e.printStackTrace();
}
// 根据实验要求,利用switch语句选不同操作的模块
boolean isTrue = true;
while (isTrue) {
System.out.println("欢迎来到身份证信息查询系统,请选择你的操作");
System.out.println("1.字典排序");
System.out.println("2.输出年龄最大和最小的人");
System.out.println("3.寻找年龄相近的人");
System.out.println("4.寻找老乡");
System.out.println("5.退出");
int nextInt = scanner.nextInt();
switch (nextInt) {
case 1:
Collections.sort(cardlist);
System.out.println(cardlist.toString());
break;
case 2:
int max = 0, min = 100;
int j, k1 = 0, k2 = 0;
for (int i = 1; i < cardlist.size(); i++) {
j = cardlist.get(i).getAge();
if (j > max) {
max = j;
k1 = i;
}
if (j < min) {
min = j;
k2 = i;
}
}
System.out.println("年龄最大:" + cardlist.get(k1));
System.out.println("年龄最小:" + cardlist.get(k2));
break;
case 3:
System.out.println("你的年龄:");
int yourage = scanner.nextInt();
int near = agenear(yourage);
System.out.println(cardlist.get(near));
break;
case 4:
System.out.println("你的家乡?");
String find = scanner.next();
String place = find.substring(0, 3);
for (int i = 0; i < cardlist.size(); i++) {
if (cardlist.get(i).getArea().substring(1, 4).equals(place))
System.out.println("老乡 " + cardlist.get(i));
}
break;
case 5:
isTrue = false;
System.out.println("程序已退出!");
break;
default:
System.out.println("输入有误");
}
}
}
//寻找年龄相近的人的位置
public static int agenear(int age) {
int j = 0, min = 100, value = 0, k = 0;
for (int i = 0; i < cardlist.size(); i++) {
value = cardlist.get(i).getAge() - age;
if (value < 0)
value = -value;
if (value < min) {
min = value;
k = i;
}
}
return k;
}
}


package ba;
//对数据具体处理的模块
public class Card implements Comparable<Card> {
private String name;
private String id;
private String sex;
private int age;
private String area;
//返回具体的数据
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
// 按名字的字典顺序排列
public int compareTo(Card c) {
return this.name.compareTo(c.getName());
}
// 用toString方法返回数据
public String toString() {
return name + "\t" + id + "\t" + sex + "\t" + age + "\t" + area + "\n";
}
}
Card
完善建议:
简化代码的行数
l 各自运行合作伙伴实验十编程练习 2,结合使用体验对所运行程序提出完善建议;
王斌龙的代码:


package 异常;
import java.io.PrintWriter;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
Demo demo=new Demo();
PrintWriter output = null;
try {
output = new PrintWriter("test.txt");
} catch (Exception e) {
e.printStackTrace();
}
int sum = 0;
for (int i = 0; i < 10; i++) {
int a = (int) Math.round(Math.random() * 100);
int b = (int) Math.round(Math.random() * 100);
int c = (int) Math.round(Math.random() * 3);
switch (c) {
case 0:
System.out.println(a + "+" + b + "=");
int d0 = in.nextInt();
output.println(a + "+" + b + "=" + d0);
if (d0 == demo.demo1(a, b)) {
sum += 10;
System.out.println("恭喜答案正确");
} else {
System.out.println("抱歉,答案错误");
}
break;
case 1:
while (a < b) {
int x = a;
a = b;
b = x;
}
System.out.println(a + "-" + b + "=");
int d1 = in.nextInt();
output.println(a + "-" + b + "=" + d1);
if (d1 == demo.demo2(a, b)) {
sum += 10;
System.out.println("恭喜答案正确");
} else {
System.out.println("抱歉,答案错误");
}
break;
case 2:
System.out.println(a + "*" + b + "=");
int d2 = in.nextInt();
output.println(a + "*" + b + "=" + d2);
if (d2 == demo.demo3(a, b)) {
sum += 10;
System.out.println("恭喜答案正确");
} else {
System.out.println("抱歉,答案错误");
}
break;
case 3:
while (b == 0 || a % b != 0) {
a = (int) Math.round(Math.random() * 100);
b = (int) Math.round(Math.random() * 100);
}
System.out.println(a + "/" + b + "=");
int d3 = in.nextInt();
output.println(a + "/" + b + "=" + d3);
if (d3 == demo.demo4(a, b)) {
sum += 10;
System.out.println("恭喜答案正确");
} else {
System.out.println("抱歉,答案错误");
}
break;
}
}
System.out.println("你的得分为" + sum);
output.println("你的得分为" + sum);
output.close();
}
}


package 异常;
public class Demo<T> {
private T a;
private T b;
public Demo() {
a = null;
b = null;
}
public Demo(T a, T b) {
this.a = a;
this.b = b;
}
public int demo1(int a, int b) {
return a + b;
}
public int demo2(int a, int b) {
return a - b;
}
public int demo3(int a, int b) {
return a * b;
}
public int demo4(int a, int b) {
return a / b;
}
}
完善建议:
个人认为,为了程序的严谨性,需要在 Demo 类中的除法计算语句(模块)中加入 “a>b,a% b==0,(a/b)%1==0” 的限制条件(语句)
l 采用结对编程方式,与学习伙伴合作完成实验九编程练习 1;


package shen;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
public class Main {
/**
* 1.文件读取模块 利用ArrayList构造studentlist存放文件内容2. 创建文件字符流,分类读取文件内容 3.try/catch语句捕获异常
*/
private static ArrayList<Student> studentlist;
public static void main(String[] args) {
studentlist = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
File file = new File("C:\\Users\\ASUS\\Desktop\\新建文件夹\\身份证号.txt");
try {
FileInputStream fis = new FileInputStream(file);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
String temp = null;
while ((temp = in.readLine()) != null) {
Scanner linescanner = new Scanner(temp);
linescanner.useDelimiter(" ");
String name = linescanner.next();
String number = linescanner.next();
String sex = linescanner.next();
String age = linescanner.next();
String province = linescanner.nextLine();
Student student = new Student();
student.setName(name);
student.setnumber(number);
student.setsex(sex);
int a = Integer.parseInt(age);
student.setage(a);
student.setprovince(province);
studentlist.add(student);
}
} catch (FileNotFoundException e) {
System.out.println("学生信息文件找不到");
e.printStackTrace();
// 加入的捕获异常代码
} catch (IOException e) {
System.out.println("学生信息文件读取错误");
e.printStackTrace();
// 加入的捕获异常代码
}
/*
* 1.根据实验要求,选择具体操作的模块 2.利用switch语句选择具体的操作
*/
boolean isTrue = true;
while (isTrue) {
System.out.println("选择你的操作,输入正确格式的选项");
System.out.println("A.字典排序");
System.out.println("B.输出年龄最大和年龄最小的人");
System.out.println("C.寻找老乡");
System.out.println("D.寻找年龄相近的人");
System.out.println("F.退出");
String m = scanner.next();
switch (m) {
case "A":
Collections.sort(studentlist);
System.out.println(studentlist.toString());
break;
case "B":
int max = 0, min = 100;
int j, k1 = 0, k2 = 0;
for (int i = 1; i < studentlist.size(); i++) {
j = studentlist.get(i).getage();
if (j > max) {
max = j;
k1 = i;
}
if (j < min) {
min = j;
k2 = i;
}
}
System.out.println("年龄最大:" + studentlist.get(k1));
System.out.println("年龄最小:" + studentlist.get(k2));
break;
case "C":
System.out.println("老家?");
String find = scanner.next();
String place = find.substring(0, 3);
for (int i = 0; i < studentlist.size(); i++) {
if (studentlist.get(i).getprovince().substring(1, 4).equals(place))
System.out.println("老乡" + studentlist.get(i));
}
break;
case "D":
System.out.println("年龄:");
int yourage = scanner.nextInt();
int near = agenear(yourage);
int value = yourage - studentlist.get(near).getage();
System.out.println("" + studentlist.get(near));
break;
case "F":
isTrue = false;
System.out.println("退出程序!");
break;
default:
System.out.println("输入有误");
}
}
}
/*
* 对年龄数据进行相应的处理
*/
public static int agenear(int age) {
int j = 0, min = 53, value = 0, k = 0;
for (int i = 0; i < studentlist.size(); i++) {
value = studentlist.get(i).getage() - age;
if (value < 0)
value = -value;
if (value < min) {
min = value;
k = i;
}
}
return k;
}
}


package shen;
/*
* 分类返回具体数据
*利用接口技术比较name的大小
*用toString方法返回数据
*/
public class Student implements Comparable<Student> {
private String name;
private String number;
private String sex;
private int age;
private String province;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getnumber() {
return number;
}
public void setnumber(String number) {
this.number = number;
}
public String getsex() {
return sex;
}
public void setsex(String sex) {
this.sex = sex;
}
public int getage() {
return age;
}
public void setage(int age) {
// int a = Integer.parseInt(age);
this.age = age;
}
public String getprovince() {
return province;
}
public void setprovince(String province) {
this.province = province;
}
public int compareTo(Student o) {
return this.name.compareTo(o.getName());
}
public String toString() {
return name + "\t" + sex + "\t" + age + "\t" + number + "\t" + province + "\n";
}
}
l 采用结对编程方式,与学习伙伴合作完成实验十编程练习 2。


package demo;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Random;
import java.util.Scanner;
public class demo {
public static void main(String[] args) {
/**
*文件输出模块
*1.调用构造函数counter
*2.创建文件字符流,将out中的内容设为空(null)
*3.将out结果输出到test.txt中
*4.try/catch模块捕获异常
*/
Scanner in = new Scanner(System.in);
yunsuan counter = new yunsuan();
PrintWriter out = null;
try {
out = new PrintWriter("text.txt");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/**
*四则运算生成模块
*1.定义一个int型sum,计算成绩,并说明生成的运算类型
*2.for语句,将{}内的内容循环10次,从而生成10道题目
*3.随机生成int型a与b,范围在0到100以内;生成int型m,范围为1,2,3,4
*4.利用switch语句,根据生成m的值,随机生成加减乘除四则运算
*5.将循环结果输出到test.txt中
*/
int sum = 0;
System.out.println("随机生成的四则运算类型");
System.out.println("类型1:除法");
System.out.println("类型2:乘法");
System.out.println("类型3:加法");
System.out.println("类型4:减法");
for (int i = 1; i <= 10; i++) {
int a = (int) Math.round(Math.random() * 100);
int b = (int) Math.round(Math.random() * 100);
int m;
Random rand = new Random();
m = (int) rand.nextInt(4) + 1;
System.out.println("随机生成的四则运算类型:"+m);
switch (m) {
case 1:
System.out.println(i + ": " + a + "/" + b + "=");
while (b == 0) {
b = (int) Math.round(Math.random() * 100);
}
double c0 = in.nextDouble();
out.println(a + "/" + b + "=" + c0);
if (c0 == counter.division(a, b)) {
sum += 10;
System.out.println("right!");
} else {
System.out.println("error!");
}
break;
case 2:
System.out.println(i + ": " + a + "*" + b + "=");
int c = in.nextInt();
out.println(a + "*" + b + "=" + c);
if (c == counter.multiplication(a, b)) {
sum += 10;
System.out.println("right!");
} else {
System.out.println("error!");
}
break;
case 3:
System.out.println(i + ": " + a + "+" + b + "=");
int c1 = in.nextInt();
out.println(a + "+" + b + "=" + c1);
if (c1 == counter.add(a, b)) {
sum += 10;
System.out.println("right!");
} else {
System.out.println("error!");
}
break;
case 4:
System.out.println(i + ": " + a + "-" + b + "=");
int c2 = in.nextInt();
out.println(a + "-" + b + "=" + c2);
if (c2 == counter.reduce(a, b)) {
sum += 10;
System.out.println("right!");
} else {
System.out.println("error!");
}
break;
}
}
System.out.println("成绩" + sum);
out.println("成绩:" + sum);
out.close();
}
}


package demo;
public class yunsuan {
private int a;
private int b;
public int add(int a,int b)
{
return a+b;
}
public int reduce(int a,int b)
{
return a-b;
}
public int multiplication(int a,int b)
{
return a*b;
}
public int division(int a,int b)
{
if(b!=0)
return a/b;
else
return 0;
}
}
运行结果:
学习总结:
集合
1. 数据结构介绍
l 般将数据结构分为两大类:线性数据结构和非线性数据结构。
l 线性数据结构:线性表、栈、队列、串、数组和文件。
l 非线性数据结构:树和图。
A. 线性表
单向链表
循环链表
双向循环链表
B. 栈(Stack)
C. 队列(Queue)
D. 散列表
2.JAVA 的集合框架
l JAVA 的集合框架实现对各种数据结构的封装,以降低对数据管理与处理的难度。
l 所谓框架就是一个类库的集合,框架中包含很多超类,编程者创建这些超类的子类可较方便的设计设计程序所需的类。例如:Swing 类包
l 集合 (Collection 或称为容器) 是一种包含多个元素并提供对所包含元素操作方法的类,其包含的元素可以由同一类型的对象组成,也可以由不同类型的对象组成。
l 集合框架:JAVA 集合类库的统一架构。
1. 集合类的作用
l 集合类的作用:
– Java 的集合类提供了一些基本数据结构的支持。
– 例如 Vector、Hashtable、Stack 等。
l 集合类的使用:
– Java 的集合类包含在 java.util 包中。
– import java.util.*;
2. 集合类的特点
l 特点一:
– 只容纳对象。
注意:数组可以容纳基本数据类型数据和对象。
– 如果集合类中想使用基本数据类型,又想利用集合类的灵活性,可以把基本数据类型数据封装成该数据类型的包装器对象,然后放入集合中处理。
l 特点二:
– 集合类容纳的对象都是 Object 类的实例,一旦把一个对象置入集合类中,它的类信息将丢失,这样设计的目的是为了集合类的通用性。
– 因为 Object 类是所有类的祖先,所以可以在这些集合中存放任何类的对象而不受限制,但切记在使用集合成员之前必须对它重新造型。
3. 新旧集合类
Vector 类
Stack 类
Hashtable 类
集合框架中的基本接口
l Collection:集合层次中的根接口,JDK 未提供这个接口的直接实现类。
l Set:不能包含重复的元素。对象可能不是按存放的次序存放,也就是说不能像数组一样按索引的方式进行访问,SortedSet 是一个按照升序排列元素的 Set。
l List:是一个有序的集合,可以包含重复的元素。提供了按索引访问的方式。
l Map:包含了 key-value 对。Map 不能包含重复的 key。
l SortedMap 是一个按照升序排列 key 的 Map。
个人感受:
通过一个周的学习,我参考数据结构中的知识,掌握了 java 中集合的概念,学习了集合的知识以及使用方法。另外,通过新的学习方式,结对编程,我们更加轻松的完成了编程任务,并与合作伙伴之间提出了积极的程序改进建议。在学习中,本人对 HashMap 和 TreeMap 仍然不是很懂,望老师能够进行回顾。
20172308《程序设计与数据结构》第十一周学习总结
20172308 2017-2018-2 《Java 程序设计》第十周学习总结
教材学习内容总结
### 第 24 章 初识 Android 1. 应用程序结构:
- 两个节点
-
app: -manifests(包含 AndroidManifest.xml 文件,描述应用程序) -java(包含所有的 Java 应用程序和测试类) -res(包含资源文件)
-
Gradle Scripts: 包含 Gradle 构件脚本
- 调试应用程序:Android.util.Log 类用于记录日志消息,L 可以将消息保存在一个文件中并过滤消息 2. 在 Android Studio 打开一个项目:File—>Open 并浏览到应用程序目录
### 第 25 章 活动 1. 启动另一个活动:注意修改 manifests.xml 文件 2. 修改应用程序图标: 在 res/drawable 中保存一张图片 jepg 或 png png 首选(支持透明度) 编辑 Android:icon 属性,指向新的图片
### 第 26 章 UI 组件 1. 基本组件:AndroidManifest.xml 文件下说明 2.toast:小的弹出对话框(一段时间会消失,可设定)
教材学习中的问题和解决过程
-
问题 1:在 Windows 系统上安装 Android Studio 步骤出现了问题,如图:
Android SDK 安装位置出现了问题,
your SDK locations contains non-ASCⅡ characters
,并且,这一步不能省略,否则无法继续后续操作,创建项目。 -
问题 1 解决过程: 通过向其他同学询问参考,发现他们并没有遇到这一阻碍。SDK 应该是自动安装的,放在程序建议的文件夹下的,因为我用 everything 查找这个文件夹的时候并没有找到,后来百度了一下问题提示,这个问题我已经不是第一次犯了,路径中有中文。
但是又有一个问题出现了,那就是如何把C盘下用户文件夹重命名。本以为鼠标左击一下就OK了,但是显然没那么简单。百度了很多资料,博客,做法很复杂,尤其是现在的win10系统,还要更改一些注册表之类的东西,我感受到了深深的危险,还想让我的电脑多活几天。。。当然还得试一试,后面会在虚拟机里尝试一下,再回来记录一下。 这一步骤的阻碍真的花费了我很多的时间去寻找解决办法,上面那个不敢用,就只能找另一个办法了----那就是随便找个文件夹放一下吧。换了之后也提示了警告注意之类的东西,说可能会发生未知的错误(话说我只要记住这个路径,应该没多大问题吧。。。),但这一步好歹是可以过去了。 可能是网速的原因吧,现在一直卡在这里,如图:
有点怕...... 【更新】。。。我的电脑已经坏了,现在一直在用系统的临时配置文件苟延残喘着,等待着 Java 的结课,然后去重 。装 。电 。脑 。系 。统 。
-
问题 2:如何在 Android Studio 中打开一个项目?
-
问题 2 解决过程:按道理来说,打开一个项目应该很简单啊:File—>Open 并浏览到应用程序目录; 然而事实上这经历了一个漫长的难熬的痛苦的费流量的过程:如图, 首先,打开 project structure
然后根据自己的 Android Studio 版本修改红色区域内的信息,如图:
接下来,就是等待时间。。。等待它下载完那个什么东西文件,然后再点击下方的那个信息提示栏里的 update,再等待一下就 OK 了。 不过信息提示栏里还是会有红色感叹号,好像是警告你什么什么东西的版权快到了,不过这并不影响程序的运行。
最后,关于这个问题的总结: 1. 这个问题的出现应该是由于导入的程序是由编写的 Android 软件的版本不同导致的,所以需要改一下版本信息 2. 当然不是每一次打开文件都要下载那个什么文件,只要第一次就好了,不过,每一次都要修改程序的版本信息 3. 似乎还有更简单的其他方法实现代码导入:比如,复 。制 。粘 。贴 。? 4. 当然了手动敲入一定没问题的啦
上周考试错题总结
-
错题 1:
-
错题 1 解析:抽象数据类型包括数据结构和操作和访问数据结构的方法。数组是一种数据结构,但是没有方法 (例如插入方法或搜索方法),而引用变量和基本类型是数据而不是数据结构。向量包括了这两种(虽然我不知道向量是什么)
-
错题 2:
-
错题 2 解析:上述选项都是面向对象的特性。一个抽象的数据类型封装了一个数据结构和处理数据结构的方法,这样信息隐藏就会被保存下来。因此,所有 ADT 都使用了信息隐藏,因此不能直接从 ADT 外部操作数据结构,而不需要其他面向对象的特性。
-
错题 3:
-
错题 3 解析:在链表中,链接是对下一个节点的引用。通过检查引用的内容来 “取消引用” 链接。
-
错题 4:
-
错题 4 解析:列表就是这样一个数据结构的一个例子 —— 因此线性数据结构可能每个节点只有一个链接。
-
错题 5:
-
错题 5 解析:抽象数据类型包括数据结构,访问 / 操作数据结构的方法。
-
错题 6:
-
错题 6 解析:虽然这两个操作都是各自抽象数据类型的 “添加” 或 “插入” 操作,但它们的不同之处在于 push 总是在堆栈的顶部添加,而 enqueue 总是在队列的后部添加。(这题很坑)
-
错题 7:
-
错题 7 解析:数组是一个数据结构,可以用来存储一个值列表,但是数组没有已经实现的操作来执行列表操作(即方法)
-
错题 8:
-
错题 8 解析:要将其视为抽象数据类型,类型必须定义数据结构和操作数据结构的方法。
-
错题 9:
-
错题 9 解析:使用 man 3 printf 命令可以查看 C 语言中的 printf 函数的帮助文档。
-
错题 10:
-
错题 10 解析:可以。。。
-
错题 11:
-
错题 11 解析:chmod 777 pdds,不是 chomd 777 pdds(这题很可以。。。)
-
错题 12:
-
错题 12 解析:rm –f /dky/D*
-
错题 13:
-
错题 13 解析:正确的。。。
-
错题 14:
-
错题 14 解析:正确答案:grep –rn main /src
结对及互评
-
博客中值得学习的或问题:
- 侯泽洋同学的博客排版工整,界面很美观
- 问题总结做得很全面
- 对于书上的疑惑总会想办法解决它,这种探索的精神值得我去学习
-
代码中值得学习的或问题:
- 对于编程的编写总能找到角度去解决
-
本周结对学习情况
- 20172302
- 结对学习内容
- 第 23,24,25,26 章内容:Android
学习进度条
代码行数(新增 / 累积) | 博客量(新增 / 累积) | 学习时间(新增 / 累积) | 重要成长 | |
---|---|---|---|---|
目标 | 5000 行 | 30 篇 | 400 小时 | |
第一周 | 309/309 | 1/1 | 20/20 | |
第二周 | 269/578 | 1/2 | 18/38 | |
第三周 | 236/776 | 1/3 | 22/60 | |
第四周 | 507/1283 | 2/5 | 30/90 | |
第五周 | 631/1914 | 1/6 | 30/120 | |
第六周 | 529/2443 | 1/7 | 25/145 | |
第七周 | 515/2958 | 1/8 | 25/170 | |
第八周 | 1128/4086 | 2/10 | 50/220 | |
第九周 | 1241/5327 | 1/11 | 15/235 | |
第十周 | 1852/7179 | 1/12 | 10/245 | |
第十一周 | 0/7179 | 1/13 | 15/260 |
参考资料
- Java 和 Anroid 开发学习指南(第二版)
20175227 张雪莹 2018-2019-2 《Java 程序设计》第十一周学习总结
20175227 张雪莹 2018-2019-2 《Java 程序设计》第十一周学习总结
教材学习内容总结
第十三章 Java 网络编程
-
URL 类
- 一个 URL 对象通常包含最基本的三部分信息:协议、地址、资源。
- URL 对象调用
InputStream openStream()
- 方法可以返回一个输入流,该输入流指向 URL 对象所包含的资源。通过该输入流可以将服务器上的资源读入到客户端。
-
InetAdress 类
- 获取地址
- 获取 Internet 上主机的地址
- 可以使用 InetAddress 类的静态方法
getByName(String s);
- 获取本地机的地址
- 我们可以使用 InetAddress 类的静态方法 getLocalHost () 获得一个 InetAddress 对象,该对象含有本地机的域名和 IP 地址。
- 获取本地机的地址
- 获取地址
-
套接字
- 当两个程序需要通信时,它们可以通过使用 Socket 类建立套接字对象并连接在一起(端口号与 IP 地址的组合得出一个网络套接字)。
- 建立连接到服务器的套接字对象:
try{ Socket mysocket=new Socket(“http://192.168.0.78”,1880);
}
catch(IOException e)
{ }
- 建立 ServerSocket 对象:
try{ ServerSocket serverForClient =new ServerSocket(2010);
}
catch(IOException e){}
- 使用方法
accept()
将客户的套接字和服务器端的套接字连接起来,代码如下所示:
try{ Socket sc= serverForClient .accept();
}
catch(IOException e){}
-
两个原则
- 服务器应当启动一个专门线程,在该线程中和客户的套接字建立连接
- 由于套接字的输入流在读取信息时可能发生阻碍,客户端和服务器端都需要在一个单独的线程中读取信息
-
UDP 数 据 报
- 基于 UDP 通信的基本模式是:
- 将数据打包,称为数据包(好比将信件装入信封一样),然后将数据包发往目的地。
- 接受别人发来的数据包(好比接收信封一样),然后查看数据包中的内容。
- 发送数据包
- 用 DatagramPacket 类将数据打包,即用 DatagramPacket 类创建一个对象,称为数据包。
- 用 DatagramSocket 类的不带参数的构造方法:DatagramSocket () 创建一个对象,该对象负责发送数据包。
- 基于 UDP 通信的基本模式是:
-
接收数据包
- 首先用 DatagramSocket 的另一个构造方法
DatagramSocket(int port)
创建一个对象,其中的参数必须和待接收的数据包的端口号相同。 - 然后对象 mail_in 使用方法
receive(DatagramPacket pack)
接受数据包。 - 用 DatagramPack 类的另外一个构造方法:
DatagramPack(byte data[],int length)
创建一个数据包,用于接收数据包
- 首先用 DatagramSocket 的另一个构造方法
-
广播数据报
- 广播数据报是一种较新的技术,要广播或接收广播的主机都必须加入到同一个 D 类地址。
-
Java 远程调用(RMI)
- RMI 的设计细节
- 扩展 Remote 接口
- 定义一个接口是 java.rmi 包中 Remote 的子接口,即扩展 Remote 接口。
- 扩展 Remote 接口
- 远程对象 - 创建远程对象的类必须要实现 Remote 接口,RMI 使用 Remote 接口来标识远程对象,但是 Remote 中没有方法,因此创建远程对象的类需要实现 Remote 接口的一个子接口。
- 存根(Stub)与代理:RMI 使用 rmic 命令生成存根
- 启动注册 rmiregistry: 执行 rimregistry 命令
- 启动远程对象服务:远程服务器使用 java.rmi 包中的 Naming 类调用其类方法 rebind (String name, Remote obj) 绑定一个远程对象到 rmiregistry 所管理的注册表中,该方法的 name 参数是 URL 格式,obj 参数是远程对象,将来客户端的代理会通过 name 找到远程对象 obj。
- 运行客户端程序:远程服务器启动远程对象服务后,客户端就可以运行有关程序,访问使用远程对象。
- RMI 的设计细节
教材学习中的问题和解决过程
- 无
代码调试中的问题和解决过程
- 问题 1:在运行例子 1 时,出现类错误提示
- 问题 1 解决办法:将两个程序分别打包在同一文件夹下,通过输入
javac -encoding gbk Example13_1.java
,然后成功编译并运行。
代码托管
上周考试错题总结
无
结对及互评
评分标准
-
正确使用 Markdown 语法(加 1 分):
- 不使用 Markdown 不加分
- 有语法错误的不加分(链接打不开,表格不对,列表不正确...)
- 排版混乱的不加分
-
模板中的要素齐全(加 1 分)
- 缺少 “教材学习中的问题和解决过程” 的不加分
- 缺少 “代码调试中的问题和解决过程” 的不加分
- 代码托管不能打开的不加分
- 缺少 “结对及互评” 的不能打开的不加分
- 缺少 “上周考试错题总结” 的不能加分
- 缺少 “进度条” 的不能加分
- 缺少 “参考资料” 的不能加分
-
教材学习中的问题和解决过程,一个问题加 1 分
-
代码调试中的问题和解决过程,一个问题加 1 分
-
本周有效代码超过 300 分行的(加 2 分)
- 一周提交次数少于 20 次的不加分
-
其他加分:
- 周五前发博客的加 1 分
- 感想,体会不假大空的加 1 分
- 排版精美的加一分
- 进度条中记录学习时间与改进情况的加 1 分
- 有动手写新代码的加 1 分
- 课后选择题有验证的加 1 分
- 代码 Commit Message 规范的加 1 分
- 错题学习深入的加 1 分
- 点评认真,能指出博客和代码中的问题的加 1 分
- 结对学习情况真实可信的加 1 分
-
扣分:
- 有抄袭的扣至 0 分
- 代码作弊的扣至 0 分
- 迟交作业的扣至 0 分
点评模板:
-
博客中值得学习的或问题:
-
该同学把老师上课讲过的重点列了出来,体现了自己重点学习的过程。
-
感觉感悟那一块的内容可以在具体一点,比如说具体遇到什么问题,如何解决,从中收获了什么,或是教材学习中增长的关于调试代码的经验。
-
代码中值得学习的或问题:
- 无
-
基于评分标准,我给本博客打分:XX 分。得分情况如下:xxx
点评过的同学博客和代码
-
本周结对学习情况
- 结对同学学号 20175212
-
结对照片
- 结对学习内容
- XXXX
- XXXX
- ...
- 结对学习内容
-
上周博客互评情况
学习进度条
代码行数(新增 / 累积) | 博客量(新增 / 累积) | 学习时间(新增 / 累积) | 重要成长 | |
---|---|---|---|---|
第一周 | 11/11 | 1/1 | ||
第二周 | 262/273 | 1/2 | ||
第三周 | 642/915 | 1/3 | ||
第四周 | 384/1299 | 2/5 | ||
第五周 | 661/1960 | 1/6 | ||
第六周 | 1031/2991 | 2/8 | ||
第七周 | 123/3114 | 2/10 | ||
第八周 | 941/4055 | 2/12 | ||
第九周 | 1697/5752 | 4/16 | ||
第十周 | 1148/6900 | 2/18 | ||
第十一周 | 1083/7983 | 1/19 |
参考资料
- [Java2 实用教程 (第 5 版)]
201771010101 白玛次仁《面向对象程序设计(Java)》第十一周学习总结
实验十一 集合
实验时间 2018-11-8
1、实验目的与要求
(1) 掌握 Vetor、Stack、Hashtable 三个类的用途及常用 API;
(2) 了解 java 集合框架体系组成;
(3) 掌握 ArrayList、LinkList 两个类的用途及常用 API。
(4) 了解 HashSet 类、TreeSet 类的用途及常用 API。
(5) 了解 HashMap、TreeMap 两个类的用途及常用 API;
(6) 结对编程(Pair programming)练习,体验程序开发中的两人合作。
2、实验内容和步骤
实验 1: 导入第 9 章示例程序,测试程序并进行代码注释。
测试程序 1:
l 使用 JDK 命令运行编辑、运行以下三个示例程序,结合运行结果理解程序;
l 掌握 Vetor、Stack、Hashtable 三个类的用途及常用 API。
// 示例程序 1 import java.util.Vector;
class Cat { private int catNumber;
Cat(int i) { catNumber = i; }
void print() { System.out.println("Cat #" + catNumber); } }
class Dog { private int dogNumber;
Dog(int i) { dogNumber = i; }
void print() { System.out.println("Dog #" + dogNumber); } }
public class CatsAndDogs { public static void main(String[] args) { Vector cats = new Vector(); for (int i = 0; i < 7; i++) cats.addElement(new Cat(i)); cats.addElement(new Dog(7)); for (int i = 0; i < cats.size(); i++) ((Cat) cats.elementAt(i)).print(); } } |
// 示例程序 2 import java.util.*;
public class Stacks { static String[] months = { "1", "2", "3", "4" };
public static void main(String[] args) { Stack stk = new Stack(); for (int i = 0; i < months.length; i++) stk.push(months[i]); System.out.println(stk); System.out.println("element 2=" + stk.elementAt(2)); while (!stk.empty()) System.out.println(stk.pop()); } } |
// 示例程序 3 import java.util.*;
class Counter { int i = 1;
public String toString() { return Integer.toString(i); } }
public class Statistics { public static void main(String[] args) { Hashtable ht = new Hashtable(); for (int i = 0; i < 10000; i++) { Integer r = new Integer((int) (Math.random() * 20)); if (ht.containsKey(r)) ((Counter) ht.get(r)).i++; else ht.put(r, new Counter()); } System.out.println(ht); } } |
示例程序1
package demo;
import java.util.Vector;
class Cat {
private int catNumber;
Cat(int i) {
catNumber = i;
}
void print() {
System.out.println("Cat #" + catNumber);
}
}
class Dog {
private int dogNumber;
Dog(int i) {
dogNumber = i;
}
void print() {
System.out.println("Dog #" + dogNumber);
}
}
public class CatsAndDogs {
public static void main(String[] args) {
Vector cats = new Vector();
for (int i = 0; i < 7; i++)
cats.addElement(new Cat(i));
cats.addElement(new Dog(7));
for (int i = 0; i < 7; i++)
((Cat) cats.elementAt(i)).print();
((Dog) cats.elementAt(7)).print();
}
}
import java.util.*;
public class Stacks {
static String[] months = { "1", "2", "3", "4" };
public static void main(String[] args) {
Stack stk = new Stack();
for (int i = 0; i < months.length; i++)
stk.push(months[i]);
System.out.println(stk);
System.out.println("element 2=" + stk.elementAt(2));
while (!stk.empty())
System.out.println(stk.pop());
}
}
package demo;
import java.util.*;
class Counter {
int i = 1;
//default:
public String toString() {
return Integer.toString(i);
}
}
public class Statistics {
public static void main(String[] args) {
Hashtable ht = new Hashtable();
for (int i = 0; i < 10000; i++) {
Integer r = new Integer((int) (Math.random() * 20));
//用Math.random()
if (ht.containsKey(r))
((Counter) ht.get(r)).i++;
else
ht.put(r, new Counter());
//输出r中数据的键值对出现的次数
}
System.out.println(ht);
}
}

测试程序 2
import java.util.*;
public class ArrayListDemo { public static void main(String[] argv) { ArrayList al = new ArrayList(); // Add lots of elements to the ArrayList... al.add(new Integer(11)); al.add(new Integer(12)); al.add(new Integer(13)); al.add(new String("hello")); // First print them out using a for loop. System.out.println("Retrieving by index:"); for (int i = 0; i < al.size(); i++) { System.out.println("Element " + i + " = " + al.get(i)); } } } |
import java.util.*; public class LinkedListDemo { public static void main(String[] argv) { LinkedList l = new LinkedList(); l.add(new Object()); l.add("Hello"); l.add("zhangsan"); ListIterator li = l.listIterator(0); while (li.hasNext()) System.out.println(li.next()); if (l.indexOf("Hello") < 0) System.err.println("Lookup does not work"); else System.err.println("Lookup works"); } } |
import java.util.*;
public class ArrayListDemo//ArrayList使用了数组的实现
{
public static void main(String[] argv) {
ArrayList al = new ArrayList();
//在ArrayList中添加大量元素
al.add(new Integer(11));
al.add(new Integer(12));
al.add(new Integer(13));
al.add(new String("hello"));//下标从0开始,添加4个元素
// First print them out using a for loop.
System.out.println("Retrieving by index:");
for (int i = 0; i < al.size(); i++) {
System.out.println("Element " + i + " = " + al.get(i));
}
}
}
l 在 Elipse 环境下编辑运行调试教材 360 页程序 9-1,结合程序运行结果理解程序;
l 掌握 ArrayList、LinkList 两个类的用途及常用 API。
Arraylist:
package linkedList;
import java.util.*;
/**
* This program demonstrates operations on linked lists.
* @version 1.11 2012-01-26
* @author Cay Horstmann
*/
public class LinkedListTest
{
public static void main(String[] args)
{
List<String> a = new LinkedList<>();
a.add("Amy");
a.add("Carl");
a.add("Erica");
List<String> b = new LinkedList<>();
b.add("Bob");
b.add("Doug");
b.add("Frances");
b.add("Gloria");
// merge the words from b into a
ListIterator<String> aIter = a.listIterator();
Iterator<String> bIter = b.iterator();
while (bIter.hasNext())
{
if (aIter.hasNext()) aIter.next();
aIter.add(bIter.next());
}
System.out.println(a);
// remove every second word from b
bIter = b.iterator();
while (bIter.hasNext())
{
bIter.next(); // skip one element
if (bIter.hasNext())
{
bIter.next(); // skip next element
bIter.remove(); // remove that element
}
}
System.out.println(b);
// bulk operation: remove all words in b from a
a.removeAll(b);
System.out.println(a);
}
}
测试程序 3:
l 运行 SetDemo 程序,结合运行结果理解程序;
import java.util.*; public class SetDemo { public static void main(String[] argv) { HashSet h = new HashSet (); // 也可以 Set h=new HashSet () h.add("One"); h.add("Two"); h.add("One"); // DUPLICATE h.add("Three"); Iterator it = h.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } } |
l 在 Elipse 环境下调试教材 365 页程序 9-2,结合运行结果理解程序;了解 HashSet 类的用途及常用 API。
package set;
import java.util.*;
/**
* This program uses a set to print all unique words in System.in.
* @version 1.12 2015-06-21
* @author Cay Horstmann
*/
public class SetTest
{
public static void main(String[] args)
{
Set<String> words = new HashSet<>(); // HashSet implements Set
long totalTime = 0;
try (Scanner in = new Scanner(System.in))
{
while (in.hasNext())
{
String word = in.next();
long callTime = System.currentTimeMillis();
words.add(word);
callTime = System.currentTimeMillis() - callTime;
totalTime += callTime;
}
}
Iterator<String> iter = words.iterator();
for (int i = 1; i <= 20 && iter.hasNext(); i++)
System.out.println(iter.next());
System.out.println(". . .");
System.out.println(words.size() + " distinct words. " + totalTime + " milliseconds.");
}
}
l 在 Elipse 环境下调试教材 367 页 - 368 程序 9-3、9-4,结合程序运行结果理解程序;了解 TreeSet 类的用途及常用 API。
package treeSet;
import java.util.*;
/**
* An item with a description and a part number.
*/
public class Item implements Comparable<Item>
{
private String description;
private int partNumber;
/**
* Constructs an item.
*
* @param aDescription
* the item''s description
* @param aPartNumber
* the item''s part number
*/
public Item(String aDescription, int aPartNumber)
{
description = aDescription;
partNumber = aPartNumber;
}
/**
* Gets the description of this item.
*
* @return the description
*/
public String getDescription()
{
return description;
}
public String toString()
{
return "[description=" + description + ", partNumber=" + partNumber + "]";
}
public boolean equals(Object otherObject)
{
if (this == otherObject) return true;
if (otherObject == null) return false;
if (getClass() != otherObject.getClass()) return false;
Item other = (Item) otherObject;
return Objects.equals(description, other.description) && partNumber == other.partNumber;
}
public int hashCode()
{
return Objects.hash(description, partNumber);
}
public int compareTo(Item other)
{
int diff = Integer.compare(partNumber, other.partNumber);
return diff != 0 ? diff : description.compareTo(other.description);
}
}
package treeSet;
import java.util.*;
/**
* This program sorts a set of item by comparing their descriptions.
* @version 1.12 2015-06-21
* @author Cay Horstmann
*/
public class TreeSetTest
{
public static void main(String[] args)
{
SortedSet<Item> parts = new TreeSet<>();
parts.add(new Item("Toaster", 1234));
parts.add(new Item("Widget", 4562));
parts.add(new Item("Modem", 9912));
System.out.println(parts);
NavigableSet<Item> sortByDescription = new TreeSet<>(
Comparator.comparing(Item::getDescription));
sortByDescription.addAll(parts);
System.out.println(sortByDescription);
}
}
测试程序 4:
l 使用 JDK 命令运行 HashMapDemo 程序,结合程序运行结果理解程序;
import java.util.*; public class HashMapDemo { public static void main(String[] argv) { HashMap h = new HashMap(); // The hash maps from company name to address. h.put("Adobe", "Mountain View, CA"); h.put("IBM", "White Plains, NY"); h.put("Sun", "Mountain View, CA"); String queryString = "Adobe"; String resultString = (String)h.get(queryString); System.out.println("They are located in: " + resultString); } } |
l 在 Elipse 环境下调试教材 373 页程序 9-6,结合程序运行结果理解程序;
l 了解 HashMap、TreeMap 两个类的用途及常用 API。
package map;
import java.util.*;
/**
* This program demonstrates the use of a map with key type String and value type Employee.
* @version 1.12 2015-06-21
* @author Cay Horstmann
*/
public class MapTest
{
public static void main(String[] args)
{
Map<String, Employee> staff = new HashMap<>();
staff.put("144-25-5464", new Employee("Amy Lee"));
staff.put("567-24-2546", new Employee("Harry Hacker"));
staff.put("157-62-7935", new Employee("Gary Cooper"));
staff.put("456-62-5527", new Employee("Francesca Cruz"));
// print all entries
System.out.println(staff);
// remove an entry
staff.remove("567-24-2546");
// replace an entry
staff.put("456-62-5527", new Employee("Francesca Miller"));
// look up a value
System.out.println(staff.get("157-62-7935"));
// iterate through all entries
staff.forEach((k, v) ->
System.out.println("key=" + k + ", value=" + v));
}
}
package map;
import java.util.*;
/**
* This program demonstrates the use of a map with key type String and value type Employee.
* @version 1.12 2015-06-21
* @author Cay Horstmann
*/
public class MapTest
{
public static void main(String[] args)
{
Map<String, Employee> staff = new HashMap<>();
staff.put("144-25-5464", new Employee("Amy Lee"));
staff.put("567-24-2546", new Employee("Harry Hacker"));
staff.put("157-62-7935", new Employee("Gary Cooper"));
staff.put("456-62-5527", new Employee("Francesca Cruz"));
// print all entries
System.out.println(staff);
// remove an entry
staff.remove("567-24-2546");
// replace an entry
staff.put("456-62-5527", new Employee("Francesca Miller"));
// look up a value
System.out.println(staff.get("157-62-7935"));
// iterate through all entries
staff.forEach((k, v) ->
System.out.println("key=" + k + ", value=" + v));
}
}
实验 2:结对编程练习:
l 关于结对编程:以下图片是一个结对编程场景:两位学习伙伴坐在一起,面对着同一台显示器,使用着同一键盘,同一个鼠标,他们一起思考问题,一起分析问题,一起编写程序。
l 关于结对编程的阐述可参见以下链接:
http://www.cnblogs.com/xinz/archive/2011/08/07/2130332.html
http://en.wikipedia.org/wiki/Pair_programming
l 对于结对编程中代码设计规范的要求参考:
http://www.cnblogs.com/xinz/archive/2011/11/20/2255971.html
以下实验,就让我们来体验一下结对编程的魅力。
l 确定本次实验结对编程合作伙伴;
l 各自运行合作伙伴实验九编程练习 1,结合使用体验对所运行程序提出完善建议;
穷吉
import java.io;
2 import java.io.File;
3 import java.io.FileInputStream;
4 import java.io.FileNotFoundException;
5 import java.io.IOException;
6 import java.io.InputStreamReader;
7 import java.util.ArrayList;
8 import java.util.Arrays;
9 import java.util.Collections;
10 import java.util.Scanner;
11
12 public class Test{
13 private static ArrayList<Student> studentlist;
14 public static void main(String[] args) {
15 studentlist = new ArrayList<>();
16 Scanner scanner = new Scanner(System.in);
17 File file = new File("C:\\下载\\身份证号.txt");
18 try {
19 FileInputStream fis = new FileInputStream(file);
20 BufferedReader in = new BufferedReader(new InputStreamReader(fis));
21 String temp = null;
22 while ((temp = in.readLine()) != null) {
23
24 Scanner linescanner = new Scanner(temp);
25
26 linescanner.useDelimiter(" ");
27 String name = linescanner.next();
28 String number = linescanner.next();
29 String sex = linescanner.next();
30 String age = linescanner.next();
31 String province =linescanner.nextLine();
32 Student student = new Student();
33 student.setName(name);
34 student.setnumber(number);
35 student.setsex(sex);
36 int a = Integer.parseInt(age);
37 student.setage(a);
38 student.setprovince(province);
39 studentlist.add(student);
40
41 }
42 } catch (FileNotFoundException e) {
43 System.out.println("学生信息文件找不到");
44 e.printStackTrace();
45 } catch (IOException e) {
46 System.out.println("学生信息文件读取错误");
47 e.printStackTrace();
48 }
49 boolean isTrue = true;
50 while (isTrue) {
51 System.out.println("选择你的操作,输入正确格式的选项");
52 System.out.println("1.按姓名字典序输出人员信息");
53 System.out.println("2.输出年龄最大和年龄最小的人");
54 System.out.println("3.查找老乡");
55 System.out.println("4.查找年龄相近的人");
56 System.out.println("5.退出");
57 String m = scanner.next();
58 switch (m) {
59 case "1":
60 Collections.sort(studentlist);
61 System.out.println(studentlist.toString());
62 break;
63 case "2":
64 int max=0,min=100;
65 int j,k1 = 0,k2=0;
66 for(int i=1;i<studentlist.size();i++)
67 {
68 j=studentlist.get(i).getage();
69 if(j>max)
70 {
71 max=j;
72 k1=i;
73 }
74 if(j<min)
75 {
76 min=j;
77 k2=i;
78 }
79
80 }
81 System.out.println("年龄最大:"+studentlist.get(k1));
82 System.out.println("年龄最小:"+studentlist.get(k2));
83 break;
84 case "3":
85 System.out.println("输入省份");
86 String find = scanner.next();
87 String place=find.substring(0,3);
88 for (int i = 0; i <studentlist.size(); i++)
89 {
90 if(studentlist.get(i).getprovince().substring(1,4).equals(place))
91 System.out.println("老乡"+studentlist.get(i));
92 }
93 break;
94
95 case "4":
96 System.out.println("年龄:");
97 int yourage = scanner.nextInt();
98 int near=agenear(yourage);
99 int value=yourage-studentlist.get(near).getage();
100 System.out.println(""+studentlist.get(near));
101 break;
102 case "5":
103 isTrue = false;
104 System.out.println("退出程序!");
105 break;
106 default:
107 System.out.println("输入有误");
108
109 }
110 }
111 }
112 public static int agenear(int age) {
113 int j=0,min=53,value=0,k=0;
114 for (int i = 0; i < studentlist.size(); i++)
115 {
116 value=studentlist.get(i).getage()-age;
117 if(value<0) value=-value;
118 if (value<min)
119 {
120 min=value;
121 k=i;
122 }
123 }
124 return k;
125 }
126
127 }
public class Student implements Comparable<Student> {
2
3 private String name;
4 private String number ;
5 private String sex ;
6 private int age;
7 private String province;
8
9 public String getName() {
10 return name;
11 }
12 public void setName(String name) {
13 this.name = name;
14 }
15 public String getnumber() {
16 return number;
17 }
18 public void setnumber(String number) {
19 this.number = number;
20 }
21 public String getsex() {
22 return sex ;
23 }
24 public void setsex(String sex ) {
25 this.sex =sex ;
26 }
27 public int getage() {
28
29 return age;
30 }
31 public void setage(int age) {
32 // int a = Integer.parseInt(age);
33 this.age= age;
34 }
35
36 public String getprovince() {
37 return province;
38 }
39 public void setprovince(String province) {
40 this.province=province ;
41 }
42
43 public int compareTo(Student o) {
44 return this.name.compareTo(o.getName());
45 }
46
47 public String toString() {
48 return name+"\t"+sex+"\t"+age+"\t"+number+"\t"+province+"\n";
49 }
50 }
l 各自运行合作伙伴实验十编程练习 2,结合使用体验对所运行程序提出完善建议;
穷吉
package 运算;
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
// 用户的答案要从键盘输入,因此需要一个键盘输入流
@SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
// 定义一个变量用来统计得分
int sum = 0;
// 通过循环生成10道题
for (int i = 0; i < 10; i++) {
// 随机生成两个10以内的随机数作为被除数和除数
int a = (int) Math.round(Math.random() * 10);
int b = (int) Math.round(Math.random() * 10);
System.out.println(a + "/" + b + "=");
// 定义一个整数用来接收用户输入的答案
int c = in.nextInt();
// 判断用户输入的答案是否正确,正确给10分,错误不给分
if (c == a / b) {
sum += 10;
System.out.println("恭喜答案正确");
}
else {
System.out.println("抱歉,答案错误");
}
}
//输出用户的成绩
System.out.println("你的得分为"+sum);
}
}
package 运算;
public class Yuns {
public int add(int a,int b)
{
return a+b;
}
public int reduce(int a,int b)
{
if((a-b)>0)
return a-b;
else return 0;
}
public int multiply(int a,int b)
{
return a*b;
}
public int devision(int a,int b)
{
if(b!=0)
return a/b;
else return 0;
}
l 采用结对编程方式,与学习伙伴合作完成实验九编程练习 1;
import java.io;
2 import java.io.File;
3 import java.io.FileInputStream;
4 import java.io.FileNotFoundException;
5 import java.io.IOException;
6 import java.io.InputStreamReader;
7 import java.util.ArrayList;
8 import java.util.Arrays;
9 import java.util.Collections;
10 import java.util.Scanner;
11
12 public class Test{
13 private static ArrayList<Student> studentlist;
14 public static void main(String[] args) {
15 studentlist = new ArrayList<>();
16 Scanner scanner = new Scanner(System.in);
17 File file = new File("C:\\下载\\身份证号.txt");
18 try {
19 FileInputStream fis = new FileInputStream(file);
20 BufferedReader in = new BufferedReader(new InputStreamReader(fis));
21 String temp = null;
22 while ((temp = in.readLine()) != null) {
23
24 Scanner linescanner = new Scanner(temp);
25
26 linescanner.useDelimiter(" ");
27 String name = linescanner.next();
28 String number = linescanner.next();
29 String sex = linescanner.next();
30 String age = linescanner.next();
31 String province =linescanner.nextLine();
32 Student student = new Student();
33 student.setName(name);
34 student.setnumber(number);
35 student.setsex(sex);
36 int a = Integer.parseInt(age);
37 student.setage(a);
38 student.setprovince(province);
39 studentlist.add(student);
40
41 }
42 } catch (FileNotFoundException e) {
43 System.out.println("学生信息文件找不到");
44 e.printStackTrace();
45 } catch (IOException e) {
46 System.out.println("学生信息文件读取错误");
47 e.printStackTrace();
48 }
49 boolean isTrue = true;
50 while (isTrue) {
51 System.out.println("选择你的操作,输入正确格式的选项");
52 System.out.println("1.按姓名字典序输出人员信息");
53 System.out.println("2.输出年龄最大和年龄最小的人");
54 System.out.println("3.查找老乡");
55 System.out.println("4.查找年龄相近的人");
56 System.out.println("5.退出");
57 String m = scanner.next();
58 switch (m) {
59 case "1":
60 Collections.sort(studentlist);
61 System.out.println(studentlist.toString());
62 break;
63 case "2":
64 int max=0,min=100;
65 int j,k1 = 0,k2=0;
66 for(int i=1;i<studentlist.size();i++)
67 {
68 j=studentlist.get(i).getage();
69 if(j>max)
70 {
71 max=j;
72 k1=i;
73 }
74 if(j<min)
75 {
76 min=j;
77 k2=i;
78 }
79
80 }
81 System.out.println("年龄最大:"+studentlist.get(k1));
82 System.out.println("年龄最小:"+studentlist.get(k2));
83 break;
84 case "3":
85 System.out.println("输入省份");
86 String find = scanner.next();
87 String place=find.substring(0,3);
88 for (int i = 0; i <studentlist.size(); i++)
89 {
90 if(studentlist.get(i).getprovince().substring(1,4).equals(place))
91 System.out.println("老乡"+studentlist.get(i));
92 }
93 break;
94
95 case "4":
96 System.out.println("年龄:");
97 int yourage = scanner.nextInt();
98 int near=agenear(yourage);
99 int value=yourage-studentlist.get(near).getage();
100 System.out.println(""+studentlist.get(near));
101 break;
102 case "5":
103 isTrue = false;
104 System.out.println("退出程序!");
105 break;
106 default:
107 System.out.println("输入有误");
108
109 }
110 }
111 }
112 public static int agenear(int age) {
113 int j=0,min=53,value=0,k=0;
114 for (int i = 0; i < studentlist.size(); i++)
115 {
116 value=studentlist.get(i).getage()-age;
117 if(value<0) value=-value;
118 if (value<min)
119 {
120 min=value;
121 k=i;
122 }
123 }
124 return k;
125 }
126
127 }
public class Student implements Comparable<Student> {
2
3 private String name;
4 private String number ;
5 private String sex ;
6 private int age;
7 private String province;
8
9 public String getName() {
10 return name;
11 }
12 public void setName(String name) {
13 this.name = name;
14 }
15 public String getnumber() {
16 return number;
17 }
18 public void setnumber(String number) {
19 this.number = number;
20 }
21 public String getsex() {
22 return sex ;
23 }
24 public void setsex(String sex ) {
25 this.sex =sex ;
26 }
27 public int getage() {
28
29 return age;
30 }
31 public void setage(int age) {
32 // int a = Integer.parseInt(age);
33 this.age= age;
34 }
35
36 public String getprovince() {
37 return province;
38 }
39 public void setprovince(String province) {
40 this.province=province ;
41 }
42
43 public int compareTo(Student o) {
44 return this.name.compareTo(o.getName());
45 }
46
47 public String toString() {
48 return name+"\t"+sex+"\t"+age+"\t"+number+"\t"+province+"\n";
49 }
50 }
l 采用结对编程方式,与学习伙伴合作完成实验十编程练习 2。
package 运算;
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
// 用户的答案要从键盘输入,因此需要一个键盘输入流
@SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
// 定义一个变量用来统计得分
int sum = 0;
// 通过循环生成10道题
for (int i = 0; i < 10; i++) {
// 随机生成两个10以内的随机数作为被除数和除数
int a = (int) Math.round(Math.random() * 10);
int b = (int) Math.round(Math.random() * 10);
System.out.println(a + "/" + b + "=");
// 定义一个整数用来接收用户输入的答案
int c = in.nextInt();
// 判断用户输入的答案是否正确,正确给10分,错误不给分
if (c == a / b) {
sum += 10;
System.out.println("恭喜答案正确");
}
else {
System.out.println("抱歉,答案错误");
}
}
//输出用户的成绩
System.out.println("你的得分为"+sum);
}
}
package 运算;
public class Yuns {
public int add(int a,int b)
{
return a+b;
}
public int reduce(int a,int b)
{
if((a-b)>0)
return a-b;
else return 0;
}
public int multiply(int a,int b)
{
return a*b;
}
public int devision(int a,int b)
{
if(b!=0)
return a/b;
else return 0;
}
学习总结:通过本周的学习,更懂得了 Java 的更多知识,也通过同学一起做一个实验时,更快地解决了自己没了解到的内容。
201771010112罗松《面向对象程序设计(java)》第十一周学习总结
1、实验目的与要求
(1) 掌握Vetor、Stack、Hashtable三个类的用途及常用API;
(2) 了解java集合框架体系组成;
(3) 掌握ArrayList、LinkList两个类的用途及常用API。
(4) 了解HashSet类、TreeSet类的用途及常用API。
(5)了解HashMap、TreeMap两个类的用途及常用API;
(6) 结对编程(Pair programming)练习,体验程序开发中的两人合作。
2、实验内容和步骤
实验1: 导入第9章示例程序,测试程序并进行代码注释。
测试程序1:
l 使用JDK命令运行编辑、运行以下三个示例程序,结合运行结果理解程序;
掌握Vetor、Stack、Hashtable三个类的用途及常用API。
import java.util.Vector;
//示例程序1
class Cat {
private int catNumber;
Cat(int i) {
catNumber = i;
}
void print() {
System.out.println("Cat #" + catNumber);
}
}
class Dog {
private int dogNumber;
Dog(int i) {
dogNumber = i;
}
void print() {
System.out.println("Dog #" + dogNumber);
}
}
public class CatsAndDogs {
public static void main(String[] args) {
Vector cats = new Vector();//创建一个新的类
for (int i = 0; i < 7; i++)
cats.addElement(new Cat(i));
cats.addElement(new Dog(7));
for (int i = 0; i < cats.size(); i++)
if(cats.elementAt(i)instanceof Cat)// instanceof运算符是用来指出对象是否是特定类的一个实例
{
((Cat) cats.elementAt(i)).print();
}else {
((Dog) cats.elementAt(i)).print();
}
}}
结果:
示例二:
//示例程序2
import java.util.*;
public class Stacks {
static String[] months = { "1", "2", "3", "4" };
public static void main(String[] args) {
Stack stk = new Stack();
for (int i = 0; i < months.length; i++)
stk.push(months[i]);//放入一个i值
System.out.println(stk);
System.out.println("element 2=" + stk.elementAt(2));//element表示一个节点
while (!stk.empty())
System.out.println(stk.pop());//出栈操作
}
}
Stacks
结果:
示例三:
import java.util.*;
class Counter {
int i = 1;
public String toString() {
return Integer.toString(i);
}
}
public class Statistics {
public static void main(String[] args) {
Hashtable ht = new Hashtable();//生成集合类Hashtable
for (int i = 0; i < 10000; i++) //生成循环体
{
Integer r = new Integer((int) (Math.random() * 20));//随机生成实数定义为整型
if (ht.containsKey(r))
((Counter) ht.get(r)).i++;//用来判断r是否为一个间值
else
ht.put(r, new Counter());//创建新的Counter对象
}
System.out.println(ht);
}
}
结果:
测试程序2:
l 使用JDK命令编辑运行ArrayListDemo和LinkedListDemo两个程序,结合程序运行结果理解程序;
import java.util.*;
public class ArrayListDemo {
public static void main(String[] argv) {
ArrayList al = new ArrayList();
//用Add来添加对象且可以重载
// Add lots of elements to the ArrayList...
al.add(new Integer(11));
al.add(new Integer(12));
al.add(new Integer(13));
al.add(new String("hello"));
System.out.println(al.size());//输出al的长度
// First print them out using a for loop.
System.out.println("Retrieving by index:");
for (int i = 0; i < al.size(); i++) {
System.out.println("Element " + i + " = " + al.get(i));
}
}
}
ArrayListDemo
mport java.util.*;
public class LinkedListDemo {
public static void main(String[] argv) {
LinkedList l = new LinkedList();
l.add(new Object());
l.add("Hello");
l.add("zhangsan");//add方法可以重载
ListIterator li = l.listIterator(0);//迭代器生成li对象
while (li.hasNext())//hasNext方法用来返回迭代器的对象
System.out.println(li.next());
if (l.indexOf("Hello") < 0) //生成循环语句判断最后结果
System.err.println("Lookup does not work");
else
System.err.println("Lookup works");
}
}
LinkedListDemo
测试程序3:
l 运行SetDemo程序,结合运行结果理解程序;
import java.util.*;
public class SetDemo {
public static void main(String[] argv) {
HashSet h = new HashSet(); //也可以 Set h=new HashSet()
h.add("One");
h.add("Two");
h.add("One"); // DUPLICATE
h.add("Three");
Iterator it = h.iterator();
while (it.hasNext()) //hasNext方法
{
System.out.println(it.next());
}
}
}
SetDemo
- 在Elipse环境下调试教材365页程序9-2,结合运行结果理解程序;了解HashSet类的用途及常用API。
package set;
import java.util.*;
/**
* This program uses a set to print all unique words in System.in.
* @version 1.12 2015-06-21
* @author Cay Horstmann
*/
public class SetTest
{
public static void main(String[] args)
{
Set<String> words = new HashSet<>(); // HashSet implements Set
long totalTime = 0;
try (Scanner in = new Scanner(System.in))
{
while (in.hasNext())//迭代器的用法,判断当前元素是否存在
{
String word = in.next();//指向下一个元素
long callTime = System.currentTimeMillis();
words.add(word);//
callTime = System.currentTimeMillis() - callTime;
totalTime += callTime;
}
}
Iterator<String> iter = words.iterator();//迭代器的简单实现
for (int i = 1; i <= 20 && iter.hasNext(); i++)
System.out.println(iter.next());
System.out.println(". . .");
System.out.println(words.size() + " distinct words. " + totalTime + " milliseconds.");
}
}
小结:HashSet类中存放的对象不能重复,不能保证元素的排列顺序,顺序有可能发生变化。
在Elipse环境下调试教材367页-368程序9-3、9-4,结合程序运行结果理解程序;了解TreeSet类的用途及常用API。
package treeSet;
import java.util.*;
/**
* This program sorts a set of item by comparing their descriptions.
* @version 1.12 2015-06-21
* @author Cay Horstmann
*/
public class TreeSetTest
{
public static void main(String[] args)
{
SortedSet<Item> parts = new TreeSet<>();
parts.add(new Item("Toaster", 1234));//add方法
parts.add(new Item("Widget", 4562));
parts.add(new Item("Modem", 9912));
System.out.println(parts);
NavigableSet<Item> sortByDescription = new TreeSet<>(
Comparator.comparing(Item::getDescription));
sortByDescription.addAll(parts);
System.out.println(sortByDescription);
}
}
TreeSetTest
package treeSet;
import java.util.*;
/**
* An item with a description and a part number.
*/
public class Item implements Comparable<Item>//Item类实现Comparable接口
{
private String description;
private int partNumber;
/**
* Constructs an item.
*
* @param aDescription
* the item''s description
* @param aPartNumber
* the item''s part number
*/
public Item(String aDescription, int aPartNumber)
{
description = aDescription;//字符串
partNumber = aPartNumber;
}
/**
* Gets the description of this item.
*
* @return the description
*/
public String getDescription()
{
return description;
}
public String toString()
{
return "[description=" + description + ", partNumber=" + partNumber + "]";
}//返回该对象的字符串表示
public boolean equals(Object otherObject)
{
if (this == otherObject) return true;
if (otherObject == null) return false;
if (getClass() != otherObject.getClass()) return false;
Item other = (Item) otherObject;
return Objects.equals(description, other.description) && partNumber == other.partNumber;
}
public int hashCode()
{
return Objects.hash(description, partNumber);
}
public int compareTo(Item other)
{
int diff = Integer.compare(partNumber, other.partNumber);
return diff != 0 ? diff : description.compareTo(other.description);
}
}
Item
小结:TreeSet是一种自带排序的set,TreeSet可以确保集合元素处于排序状态。TreeSet支持两种排序方式,自然排序 和定制排序。
测试程序4:
使用JDK命令运行HashMapDemo程序,结合程序运行结果理解程序;
import java.util.*;
public class HashMapDemo {
public static void main(String[] argv) {
HashMap h = new HashMap();
// The hash maps from company name to address.
h.put("Adobe", "Mountain View, CA");//定义对象
h.put("IBM", "White Plains, NY");
h.put("Sun", "Mountain View, CA");
String queryString = "Adobe";
String resultString = (String)h.get(queryString);
System.out.println("They are located in: " + resultString);
}
}
l 在Elipse环境下调试教材373页程序9-6,结合程序运行结果理解程序;
package map;
import java.util.*;
/**
* This program demonstrates the use of a map with key type String and value type Employee.
* @version 1.12 2015-06-21
* @author Cay Horstmann
*/
public class MapTest
{
public static void main(String[] args)
{
Map<String, Employee> staff = new HashMap<>();//HashMap implements Map
staff.put("144-25-5464", new Employee("Amy Lee"));
staff.put("567-24-2546", new Employee("Harry Hacker"));
staff.put("157-62-7935", new Employee("Gary Cooper"));
staff.put("456-62-5527", new Employee("Francesca Cruz"));
// print all entries
System.out.println(staff);
// remove an entry
staff.remove("567-24-2546");
// replace an entry
staff.put("456-62-5527", new Employee("Francesca Miller"));
// look up a value
System.out.println(staff.get("157-62-7935"));
// iterate through all entries
staff.forEach((k, v) ->
System.out.println("key=" + k + ", value=" + v));
}
}
l 实验2:结对编程练习:
关于结对编程:以下图片是一个结对编程场景:两位学习伙伴坐在一起,面对着同一台显示器,使用着同一键盘,同一个鼠标,他们一起思考问题,一起分析问题,一起编写程序。
l 关于结对编程的阐述可参见以下链接:
http://www.cnblogs.com/xinz/archive/2011/08/07/2130332.html
http://en.wikipedia.org/wiki/Pair_programming
l 对于结对编程中代码设计规范的要求参考:
http://www.cnblogs.com/xinz/archive/2011/11/20/2255971.html
以下实验,就让我们来体验一下结对编程的魅力
l 确定本次实验结对编程合作伙伴;
l 各自运行合作伙伴实验九编程练习1,结合使用体验对所运行程序提出完善建议;
l 各自运行合作伙伴实验十编程练习2,结合使用体验对所运行程序提出完善建议;
1、合作伙伴:张云飞
- 采用结对编程方式,与学习伙伴合作完成实验九编程练习1;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.Collections;//对集合进行排序、查找、修改等;
public class Test {
private static ArrayList<Citizen> citizenlist;
public static void main(String[] args) {
citizenlist = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
File file = new File("E:/java/身份证号.txt");
//异常捕获
try {
FileInputStream fis = new FileInputStream(file);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
String temp = null;
while ((temp = in.readLine()) != null) {
Scanner linescanner = new Scanner(temp);
linescanner.useDelimiter(" ");
String name = linescanner.next();
String id = linescanner.next();
String sex = linescanner.next();
String age = linescanner.next();
String birthplace = linescanner.nextLine();
Citizen citizen = new Citizen();
citizen.setName(name);
citizen.setId(id);
citizen.setSex(sex);
// 将字符串转换成10进制数
int ag = Integer.parseInt(age);
citizen.setage(ag);
citizen.setBirthplace(birthplace);
citizenlist.add(citizen);
}
} catch (FileNotFoundException e) {
System.out.println("信息文件找不到");
e.printStackTrace();
} catch (IOException e) {
System.out.println("信息文件读取错误");
e.printStackTrace();
}
boolean isTrue = true;
while (isTrue) {
System.out.println("1.按姓名字典序输出人员信息");
System.out.println("2.查询最大年龄的人员信息、查询最小年龄人员信息");
System.out.println("3.查询人员中是否查询人员中是否有你的同乡");
System.out.println("4.输入你的年龄,查询文件中年龄与你最近人的姓名、身份证号、年龄、性别和出生地");
System.out.println("5.退出");
int nextInt = scanner.nextInt();
switch (nextInt) {
case 1:
Collections.sort(citizenlist);
System.out.println(citizenlist.toString());
break;
case 2:
int max = 0, min = 100;
int m, k1 = 0, k2 = 0;
for (int i = 1; i < citizenlist.size(); i++) {
m = citizenlist.get(i).getage();
if (m > max) {
max = m;
k1 = i;
}
if (m < min) {
min = m;
k2 = i;
}
}
System.out.println("年龄最大:" + citizenlist.get(k1));
System.out.println("年龄最小:" + citizenlist.get(k2));
break;
case 3:
System.out.println("出生地:");
String find = scanner.next();
String place = find.substring(0, 3);
for (int i = 0; i < citizenlist.size(); i++) {
if (citizenlist.get(i).getBirthplace().substring(1, 4).equals(place))
System.out.println("出生地" + citizenlist.get(i));
}
break;
case 4:
System.out.println("年龄:");
int yourage = scanner.nextInt();
int near = peer(yourage);
int j = yourage - citizenlist.get(near).getage();
System.out.println("" + citizenlist.get(near));
break;
case 5:
isTrue = false;
System.out.println("程序已退出!");
break;
default:
System.out.println("输入有误");
}
}
}
public static int peer(int age) {
int flag = 0;
int min = 53, j = 0;
for (int i = 0; i < citizenlist.size(); i++) {
j = citizenlist.get(i).getage() - age;
if (j < 0)
j = -j;
if (j < min) {
min = j;
flag = i;
}
}
return flag;
}
}
test
public class Citizen implements Comparable<Citizen> {
private String name;
private String id;
private String sex;
private int age;
private String birthplace;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getage() {
return age;
}
public void setage(int age) {
this.age = age;
}
public String getBirthplace() {
return birthplace;
}
public void setBirthplace(String birthplace) {
this.birthplace = birthplace;
}
public int compareTo(Citizen other) {
return this.name.compareTo(other.getName());
}
public String toString() {
return name + "\t" + sex + "\t" + age + "\t" + id + "\t" + birthplace + "\n";
}
}
citizen
l 各自运行合作伙伴实验十编程练习2,结合使用体验对所运行程序提出完善建议;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class calculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Count count=new Count();
PrintWriter out = null;
try {
out = new PrintWriter("test.txt");
int sum = 0;
for (int i = 1; i <=10; i++) {
int a = (int) Math.round(Math.random() * 100);
int b = (int) Math.round(Math.random() * 100);
int menu = (int) Math.round(Math.random() * 3);
switch (menu) {
case 0:
System.out.println(i+":"+a + "+" + b + "=");
int c1 = in.nextInt();
out.println(a + "+" + b + "=" + c1);
if (c1 == (a + b)) {
sum += 10;
System.out.println("恭喜答案正确");
} else {
System.out.println("抱歉,答案错误");
}
break;
case 1:
while (a < b) {
b = (int) Math.round(Math.random() * 100);
}
System.out.println(i+":"+a + "-" + b + "=");
int c2 = in.nextInt();
out.println(a + "-" + b + "=" + c2);
if (c2 == (a - b)) {
sum += 10;
System.out.println("恭喜答案正确");
} else {
System.out.println("抱歉,答案错误");
}
break;
case 2:
System.out.println(i+":"+a + "*" + b + "=");
int c3 = in.nextInt();
out.println(a + "*" + b + "=" + c3);
if (c3 == a * b) {
sum += 10;
System.out.println("恭喜答案正确");
} else {
System.out.println("抱歉,答案错误");
}
break;
case 3:
while(b == 0){
b = (int) Math.round(Math.random() * 100);
}
while(a % b != 0){
a = (int) Math.round(Math.random() * 100);
}
System.out.println(i+":"+a + "/" + b + "=");
int c4 = in.nextInt();
if (c4 == a / b) {
sum += 10;
System.out.println("恭喜答案正确");
} else {
System.out.println("抱歉,答案错误");
}
break;
}
}
System.out.println("你的得分为" + sum);
out.println("你的得分为" + sum);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
calculate
public class Count<T> {
private T a;
private T b;
public Count() {
a=null;
b=null;
}
public Count(T a,T b) {
this.a=a;
this.b=b;
}
public int count1(int a,int b) {
return a+b;
}
public int count2(int a,int b) {
return a-b;
}
public int count3(int a,int b) {
return a*b;
}
public int count4(int a,int b) {
return a/b;
}
}
count
l 采用结对编程方式,与学习伙伴合作完成实验九编程练习1;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Xinxi {
private static ArrayList<Student> studentlist;
public static void main(String[] args) {
studentlist = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
File file = new File("D:\\身份证号\\身份证号.txt");
try {
FileInputStream fis = new FileInputStream(file);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
String temp = null;
while ((temp = in.readLine()) != null) {
Scanner linescanner = new Scanner(temp);
linescanner.useDelimiter(" ");
String name = linescanner.next();
String number = linescanner.next();
String sex = linescanner.next();
String age = linescanner.next();
String province = linescanner.nextLine();
Student student = new Student();
student.setName(name);
student.setnumber(number);
student.setsex(sex);
int a = Integer.parseInt(age);
student.setage(a);
student.setprovince(province);
studentlist.add(student);
}
} catch (FileNotFoundException e) {//添加的异常处理语句try{ }catch{ }语句
System.out.println("所找信息文件找不到");
e.printStackTrace();
} catch (IOException e) {
System.out.println("所找信息文件读取错误");//采取积极方法捕获异常,并将异常返回自己所设定的打印文字
e.printStackTrace();
}
boolean isTrue = true;
while (isTrue) {
System.out.println("选择你的操作,输入正确格式的选项");
System.out.println("1按姓名字典序输出人员信息");
System.out.println("2.查询最大和最小年龄的人员信息");
System.out.println("3.寻找年龄相近的人的信息");
System.out.println("4.寻找老乡");
System.out.println("5.退出");
String n = scanner.next();
switch (n) {
case "1":
Collections.sort(studentlist);
System.out.println(studentlist.toString());
break;
case "2":
int max = 0, min = 100;
int j, k1 = 0, k2 = 0;
for (int i = 1; i < studentlist.size(); i++) {
j = studentlist.get(i).getage();
if (j > max) {
max = j;
k1 = i;
}
if (j < min) {
min = j;
k2 = i;
}
}
System.out.println("年龄最大:" + studentlist.get(k1));
System.out.println("年龄最小:" + studentlist.get(k2));
break;
case "3":
System.out.println("家乡在哪里?");
String find = scanner.next();
String place = find.substring(0, 3);
for (int i = 0; i < studentlist.size(); i++) {
if (studentlist.get(i).getprovince().substring(1, 4).equals(place))
System.out.println("同乡" + studentlist.get(i));
}
break;
case "4":
System.out.println("年龄:");
int yourage = scanner.nextInt();
int near = agenear(yourage);
int value = yourage - studentlist.get(near).getage();
System.out.println("" + studentlist.get(near));
break;
case "5":
isTrue = false;
System.out.println("退出程序!");
break;
default:
System.out.println("输入有误");
}
}
}
public static int agenear(int age) {
int j = 0, min = 53, value = 0, flag = 0;
for (int i = 0; i < studentlist.size(); i++) {
value = studentlist.get(i).getage() - age;
if (value < 0)
value = -value;
if (value < min) {
min = value;
flag = i;
}
}
return flag;
}
}
xinxi
xinxi
public class Student implements Comparable<Student> {
private String name;
private String number;
private String sex;
private String province;
private int age;
public void setName(String name) {
// TODO 自动生成的方法存根
this.name = name;
}
public String getName() {
// TODO 自动生成的方法存根
return name;
}
public void setnumber(String number) {
// TODO 自动生成的方法存根
this.number = number;
}
public String getNumber() {
// TODO 自动生成的方法存根
return number;
}
public void setsex(String sex) {
// TODO 自动生成的方法存根
this.sex = sex;
}
public String getsex() {
// TODO 自动生成的方法存根
return sex;
}
public void setprovince(String province) {
// TODO 自动生成的方法存根
this.province = province;
}
public String getprovince() {
// TODO 自动生成的方法存根
return province;
}
public void setage(int a) {
// TODO 自动生成的方法存根
this.age = age;
}
public int getage() {
// TODO 自动生成的方法存根
return age;
}
public int compareTo(Student o) {
return this.name.compareTo(o.getName());
}
public String toString() {
return name + "\t" + sex + "\t" + age + "\t" + number + "\t" + province + "\n";
}
}
student类
student
l 采用结对编程方式,与学习伙伴合作完成实验十编程练习2。
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class calculator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Count count=new Count();
PrintWriter out = null;
try {
out = new PrintWriter("test.txt");
int sum = 0;
for (int i = 1; i <=10; i++) {
int a = (int) Math.round(Math.random() * 100);
int b = (int) Math.round(Math.random() * 100);
int menu = (int) Math.round(Math.random() * 3);
switch (menu) {
case 0:
System.out.println(i+":"+a + "+" + b + "=");
int c1 = in.nextInt();
out.println(a + "+" + b + "=" + c1);
if (c1 == (a + b)) {
sum += 10;
System.out.println("恭喜答案正确");
} else {
System.out.println("抱歉,答案错误");
}
break;
case 1:
while (a < b) {
b = (int) Math.round(Math.random() * 100);
}
System.out.println(i+":"+a + "-" + b + "=");
int c2 = in.nextInt();
out.println(a + "-" + b + "=" + c2);
if (c2 == (a - b)) {
sum += 10;
System.out.println("恭喜答案正确");
} else {
System.out.println("抱歉,答案错误");
}
break;
case 2:
System.out.println(i+":"+a + "*" + b + "=");
int c3 = in.nextInt();
out.println(a + "*" + b + "=" + c3);
if (c3 == a * b) {
sum += 10;
System.out.println("恭喜答案正确");
} else {
System.out.println("抱歉,答案错误");
}
break;
case 3:
while(b == 0){
b = (int) Math.round(Math.random() * 100);
}
while(a % b != 0){
a = (int) Math.round(Math.random() * 100);
}
System.out.println(i+":"+a + "/" + b + "=");
int c4 = in.nextInt();
if (c4 == a / b) {
sum += 10;
System.out.println("恭喜答案正确");
} else {
System.out.println("抱歉,答案错误");
}
break;
}
}
System.out.println("你的得分为" + sum);
out.println("你的得分为" + sum);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
calculate
public class Count<T> {
private T a;
private T b;
public Count() {
a=null;
b=null;
}
public Count(T a,T b) {
this.a=a;
this.b=b;
}
public int count1(int a,int b) {
return a+b;
}
public int count2(int a,int b) {
return a-b;
}
public int count3(int a,int b) {
return a*b;
}
public int count4(int a,int b) {
return a/b;
}
}
count
实验总结:
通过这周的学习,我对Vetor、Stack、Hashtable三个类的用途及常用API有了大致的了解,还大致了解了java集合框架体系组成;基本 掌握ArrayList、LinkList两个类的用途及常用API。了解了HashSet类、TreeSet类的用途及常用API和HashMap、TreeMap两个类的用途及常用API;
不过上述这些都只是有了一个初步的了解,要做到运用自如还要深入研究,苦下功夫。这周学习还有个最大的不同就是体验了程序开发中两人合作的感觉,从有意见不同到最后解决,那个过程很让人享受,有种竞争感和成就感,总之这周收获很大,今后的学习会更加努力!
今天的关于王颖奇 20171010129《面向对象程序设计和java》第十一周学习总结的分享已经结束,谢谢您的关注,如果想了解更多关于20172308《程序设计与数据结构》第十一周学习总结、20175227 张雪莹 2018-2019-2 《Java 程序设计》第十一周学习总结、201771010101 白玛次仁《面向对象程序设计(Java)》第十一周学习总结、201771010112罗松《面向对象程序设计(java)》第十一周学习总结的相关知识,请在本站进行查询。
本文标签: