码迷,mamicode.com
首页 > 编程语言 > 详细

王志成/王之泰《面向对象程序设计(java)》第十一周学习总结

时间:2018-11-11 15:05:52      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:generate   input   author   can   image   个数   结果   体系   教材   

理论学习部分:

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类

Vector类 
? Vector类类似长度可变的数组。
? Vector中只能存放对象。 ? Vector的元素通过下标进行访问。
? Vector类关键属性: – capacity表示集合最多能容纳的元素个数。 – capacityIncrement表示每次增加多少容量。 – size表示集合当前元素个数。
Vector v = new Vector(100)

1、实验目的与要求

(1) 掌握VetorStackHashtable三个类的用途及常用API

(2) 了解java集合框架体系组成;

(3) 掌握ArrayListLinkList两个类的用途及常用API

(4) 了解HashSet类、TreeSet类的用途及常用API

(5)了解HashMapTreeMap两个类的用途及常用API

(6) 结对编程(Pair programming练习,体验程序开发中的两人合作

2、实验内容和步骤

实验1 导入第9章示例程序,测试程序并进行代码注释。

测试程序1:

使用JDK命令运行编辑、运行以下三个示例程序,结合运行结果理解程序;

掌握VetorStackHashtable三个类的用途及常用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();
    }
}

技术分享图片

修改为:

package 王志成;

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();
            
            }
        }
            
    
    }
}

 

技术分享图片

 

package 王志成;
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 王志成;

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);
    }
}

技术分享图片

测试程序2:

使用JDK命令编辑运行ArrayListDemoLinkedListDemo两个程序,结合程序运行结果理解程序;

package 王志成;
import java.util.*;

public class ArrayListDemo {
    public static void main(String[] argv) {
        ArrayList<Comparable> 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));
        }
    }
}

技术分享图片

 

package 王志成;

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");
   }
}

技术分享图片

Elipse环境下编辑运行调试教材360页程序9-1,结合程序运行结果理解程序;

掌握ArrayListLinkList两个类的用途及常用API

package 王志成;

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:

运行SetDemo程序,结合运行结果理解程序;

package 王志成;
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());
        }
    }
}

技术分享图片

Elipse环境下调试教材365页程序9-2,结合运行结果理解程序;了解HashSet类的用途及常用API

Elipse环境下调试教材367-368程序9-39-4,结合程序运行结果理解程序;了解TreeSet类的用途及常用API

 

package 王志成;

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.");
   }
}

 

 

 

Elipse环境下调试教材367-368程序9-39-4,结合程序运行结果理解程序;了解TreeSet类的用途及常用API

package 王志成;

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 王志成;

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);
   }
}


 

 

技术分享图片

测试程序4:

使用JDK命令运行HashMapDemo程序,结合程序运行结果理解程序;

package 王志成;
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);
  }
}

技术分享图片

Elipse环境下调试教材373页程序9-6,结合程序运行结果理解程序;

了解HashMapTreeMap两个类的用途及常用API

 

package 王志成;

import java.util.*;

/**
 * This program demonstrates how to extend the collections framework.
 * @version 1.21 2012-01-26
 * @author Cay Horstmann
 */
public class CircularArrayQueueTest
{
   public static void main(String[] args)
   {
      Queue<String> q = new CircularArrayQueue<>(5);
      q.add("Amy");
      q.add("Bob");
      q.add("Carl");
      q.add("Deedee");
      q.add("Emile");
      q.remove();
      q.add("Fifi");
      q.remove();
      for (String s : q) System.out.println(s);
   }
}

/** 
    A first-in, first-out bounded collection. 
*/ 
class CircularArrayQueue<E> extends AbstractQueue<E>
{ 
   private Object[] elements; 
   private int head; 
   private int tail; 
   private int count; 
   private int modcount;

   /** 
       Constructs an empty queue. 
       @param capacity the maximum capacity of the queue 
   */ 
   public CircularArrayQueue(int capacity) 
   { 
      elements = new Object[capacity]; 
      count = 0; 
      head = 0; 
      tail = 0; 
   } 

   public boolean offer(E newElement) 
   { 
      assert newElement != null;
      if (count < elements.length) 
      {
         elements[tail] = newElement; 
         tail = (tail + 1) % elements.length; 
         count++;
         modcount++;
         return true;
      }
      else 
         return false;
   } 

   public E poll() 
   { 
      if (count == 0) return null;
      E r = peek(); 
      head = (head + 1) % elements.length; 
      count--; 
      modcount++;
      return r; 
   } 

   @SuppressWarnings("unchecked")
   public E peek() 
   { 
      if (count == 0) return null;
      return (E) elements[head]; 
   } 

   public int size() 
   { 
      return count; 
   } 

   public Iterator<E> iterator()
   {
      return new QueueIterator();
         
   }

   private class QueueIterator implements Iterator<E>
   {
      private int offset;
      private int modcountAtConstruction;

      public QueueIterator()
      {
         modcountAtConstruction = modcount;
      }

      @SuppressWarnings("unchecked")
      public E next() 
      { 
         if (!hasNext()) throw new NoSuchElementException();
         E r = (E) elements[(head + offset) % elements.length]; 
         offset++;
         return r;
      }

      public boolean hasNext() 
      { 
         if (modcount != modcountAtConstruction) 
            throw new ConcurrentModificationException();
         return offset < count;
      }

      public void remove() 
      { 
         throw new UnsupportedOperationException(); 
      }
   }
}

 

技术分享图片

实验2:结对编程练习:

关于结对编程:以下图片是一个结对编程场景:两位学习伙伴坐在一起,面对着同一台显示器,使用着同一键盘,同一个鼠标,他们一起思考问题,一起分析问题,一起编写程序。

技术分享图片

 

关于结对编程的阐述可参见以下链接:

 

http://www.cnblogs.com/xinz/archive/2011/08/07/2130332.html

http://en.wikipedia.org/wiki/Pair_programming

对于结对编程中代码设计规范的要求参考

http://www.cnblogs.com/xinz/archive/2011/11/20/2255971.html

 

以下实验,就让我们来体验一下结对编程的魅力。

确定本次实验结对编程合作伙伴;

各自运行合作伙伴实验九编程练习1,结合使用体验对所运行程序提出完善建议;

各自运行合作伙伴实验十编程练习2,结合使用体验对所运行程序提出完善建议;

合作伙伴:王之泰

合作伙伴的实验代码及结果如下:

实验九:

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{
    private static ArrayList<person> Personlist;
    public static void main(String[] args) {
        Personlist = 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 ID = linescanner.next();
                String sex = linescanner.next();
                String age = linescanner.next();
                String place =linescanner.nextLine();
                person Person = new person();
                Person.setname(name);
                Person.setID(ID);
                Person.setsex(sex);
                int a = Integer.parseInt(age);
                Person.setage(a);
                Person.setbirthplace(place);
                Personlist.add(Person);

            }
        } 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(Personlist);
                System.out.println(Personlist.toString());
                break;
            case 2:
                
                int max=0,min=100;int j,k1 = 0,k2=0;
                for(int i=1;i<Personlist.size();i++)
                {
                    j=Personlist.get(i).getage();
                   if(j>max)
                   {
                       max=j; 
                       k1=i;
                   }
                   if(j<min)
                   {
                       min=j; 
                       k2=i;
                   }

                }  
                System.out.println("年龄最大:"+Personlist.get(k1));
                System.out.println("年龄最小:"+Personlist.get(k2));
                break;
            case 3:
                System.out.println("年龄:");
                int yourage = scanner.nextInt();
                int near=agenear(yourage);
                int d=yourage-Personlist.get(near).getage();
                System.out.println(""+Personlist.get(near));
                break;
            case 4:
                System.out.println("你的家乡?");
                String find = scanner.next();        
                String place=find.substring(0,3);
                String place2=find.substring(0,3);
                for (int i = 0; i <Personlist.size(); i++) 
                {
                    if(Personlist.get(i).getbirthplace().substring(1,4).equals(place)) 
                        System.out.println(""+Personlist.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=53,d=0,k=0;
        for (int i = 0; i < Personlist.size(); i++)
        {
            d=Personlist.get(i).getage()-age;
            if(d<0) d=-d; 
            if (d<min) 
            {
               min=d;
               k=i;
            }

         }    return k;
        
     }

 
}
public class person implements Comparable<person> {
private String name;
private String ID;
private int age;
private String sex;
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 int getage() {

return age;
}
public void setage(int age) {
    // int a = Integer.parseInt(age);
this.age= age;
}
public String getsex() {
return sex;
}
public void setsex(String sex) {
this.sex= sex;
}
public String getbirthplace() {
return birthplace;
}
public void setbirthplace(String birthplace) {
this.birthplace= birthplace;
}

public int compareTo(person o) {
   return this.name.compareTo(o.getname());

}

public String toString() {
    return  name+"\t"+sex+"\t"+age+"\t"+ID+"\t"+birthplace+"\n";

}



}

 

技术分享图片技术分享图片技术分享图片

 实验十


import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.Scanner;



public class ss {
public static void main(String[] args) {



Scanner in = new Scanner(System.in);
Calculator<Integer> sf = new Calculator<Integer>();
File file = new File("wzt.txt");
if(file.exists()) {
System.out.println("文件已存在");
}
PrintWriter output = null;
try {
output = new PrintWriter(new FileOutputStream(file));
} catch (Exception e) {
//e.printStackTrace();
}
int sum = 0;

System.out.println("计算结果保留两位小数");
for (int i = 1; i < 11; i++) {
int a = (int) Math.round(Math.random() * 100);
int b = (int) Math.round(Math.random() * 100);
int s = (int) Math.round(Math.random() * 3);



switch(s)
{
case 1:
System.out.println(i+": "+a+"/"+b+"=");
Number c = in.nextDouble();
output.println(a+"/"+b+"="+c);
Number g = sf.division(a, b);
BigDecimal division = new BigDecimal(g.doubleValue());
g = division.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
if (c.equals(g)) {
sum += 10;
System.out.println("恭喜答案正确");
}
else {
System.out.println("抱歉,答案错误");
}

break;

case 2:
System.out.println(i+": "+a+"*"+b+"=");
Number c1 = in.nextDouble();
output.println(a+"*"+b+"="+c1);
Number g1 = sf.mulitiplication(a, b);
BigDecimal mul = new BigDecimal(g1.doubleValue());
g1 = mul.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
if (c1.equals(g1) ){
sum += 10;
System.out.println("恭喜答案正确");
}
else {
System.out.println("抱歉,答案错误");
}
break;
case 3:
System.out.println(i+": "+a+"+"+b+"=");
Number c2 = in.nextDouble();
output.println(a+"+"+b+"="+c2);
Number g2 =sf.addition(a, b);
BigDecimal add = new BigDecimal(g2.doubleValue());
g2 = add.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
if (c2.equals(g2)) {
sum += 10;
System.out.println("恭喜答案正确");
}
else {
System.out.println("抱歉,答案错误");
}

break ;
case 4:
System.out.println(i+": "+a+"-"+b+"=");
Number c3 = in.nextDouble();
output.println(a+"-"+b+"="+c3);
Number g3 = sf.subtraction(a, b);
BigDecimal sub = new BigDecimal(g3.doubleValue());
g3 = sub.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
if (c3.equals(g3)) {
sum += 10;
System.out.println("恭喜答案正确");
}
else {
System.out.println("抱歉,答案错误");
}
break ;


}

}
System.out.println("成绩"+sum);
output.println("成绩:"+sum);
output.close();
in.close();

}
}


public class Calculator<T> {
    
    public Calculator() {
        // TODO Auto-generated constructor stub
    }
    
    
    public Number addition(T m,T n) {
        return Double.parseDouble(m.toString())+Double.parseDouble(n.toString());
    }

    public Number subtraction(T m,T n) {
        return Double.parseDouble(m.toString())-Double.parseDouble(n.toString());
    }
    public Number mulitiplication(T m,T n) {
        return Double.parseDouble(m.toString())*Double.parseDouble(n.toString());
    }
    public Number division(T m,T n) {
        if(Double.parseDouble(n.toString()) != 0)
        return Double.parseDouble(m.toString())/Double.parseDouble(n.toString());
        else
        return 0;
    }
}

技术分享图片

完善意见:通过运行他的实验代码,可以看出他的代码写得很完善,很严谨,但或许会有一丝繁琐,可以适当的简化,但对现阶段的我们来说,这样或许更好的能帮助我们加深所学知识的理解。

 

结对编程代码如下:

package jiedui_bianchen;

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.Scanner;
import java.util.Collections;

public class ID {

    public static People findPeopleByname(String name) {
        People flag = null;
        for (People people : peoplelist) {
            if(people.getName().equals(name)) {
                flag = people;
            }
        }
        return flag;

    }

    public static People findPeopleByid(String id) {
        People flag = null;
        for (People people : peoplelist) {
            if(people.getnumber().equals(id)) {
                flag = people;
            }
        }
        return flag;

    }
     
    private static ArrayList<People> agenear(int yourage) {
        // TODO Auto-generated method stub
        int j=0,min=53,d_value=0,k = 0;
        ArrayList<People> plist = new ArrayList<People>();
        for (int i = 0; i < peoplelist.size(); i++) {
            d_value = peoplelist.get(i).getage() > yourage ? 
                    peoplelist.get(i).getage() - yourage : yourage - peoplelist.get(i).getage() ;
            k = d_value < min ? i : k;
            min = d_value < min ? d_value : min;
        }
        for(People people : peoplelist) {
            if(people.getage() == peoplelist.get(k).getage()) {
                plist.add(people);
            }
        }
        return plist;
    }

    private static ArrayList<People> peoplelist; 
    
    public static void main(String[] args) //throws  IOException
    {
        peoplelist = new ArrayList<People>();
        Scanner scanner = new Scanner(System.in);
        File file = new File("D:\\身份证号.txt");
        try {
            FileInputStream files = new FileInputStream(file);
            BufferedReader in = new BufferedReader(new InputStreamReader(files));
            String temp = null;
            while ((temp = in.readLine()) != null) {
                
                String[] information = temp.split("[ ]+");
                People people = new People();
                people.setName(information[0]);
                people.setnumber(information[1]);
                int A = Integer.parseInt(information[3]);
                people.setage(A);
                people.setsex(information[2]);
                for(int j = 4; j<information.length;j++) {
                    people.setplace(information[j]);
                }
                peoplelist.add(people);

            }
        } catch (FileNotFoundException e) {
            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.输入你的年龄,查询身份证号.txt中年龄与你最近的人");
            System.out.println("   5.查询人员中是否有你的同乡");
            System.out.println("   6.退出");
            System.out.println("******************************************");
            int nextInt = scanner.nextInt();
            switch (nextInt) {
            case 1:
                Collections.sort(peoplelist);
                System.out.println(peoplelist.toString());
                break;
            case 2:
                int max=0;
                int j,k1 = 0;
                for(int i=1;i<peoplelist.size();i++)
                {
                    j = peoplelist.get(i).getage();
                   if(j>max)
                   {
                       max = j; 
                       k1 = i;
                   }
                  
                }  
                System.out.println("年龄最大:"+peoplelist.get(k1));
                break;
            case 3:
                int min = 100;
                int j1,k2 = 0;
                for(int i=1;i<peoplelist.size();i++)
                {
                    j1 = peoplelist.get(i).getage();
                    if(j1<min)
                    {
                        min = j1; 
                        k2 = i;
                    }

                 } 
                System.out.println("年龄最小:"+peoplelist.get(k2));
                break;
            case 4:
                System.out.println("年龄:");
                int input_age = scanner.nextInt();
                ArrayList<People> plist = new ArrayList<People>();
                plist = agenear(input_age);
                for(People people : plist) {
                    System.out.println(people.toString());
                }
                break;
            case 5:
                System.out.println("请输入省份");
                String find = scanner.next();        
                for (int i = 0; i <peoplelist.size(); i++) 
                {
                    String [] place = peoplelist.get(i).getplace().split("\t");
                    for(String temp : place) {
                        if(find.equals(temp)) {
                            System.out.println("你的同乡是    "+peoplelist.get(i));
                            break;
                        }
                    }
                    
                } 
                break;
            case 6:
                isTrue = false;
                System.out.println("byebye!");
                break;
            default:
                System.out.println("输入有误");
            }
        }
    }

}

结对程序运行功能界面截图;

技术分享图片

结对过程描述,提供两人在讨论、细化和编程时的结对照片(非摆拍)。

技术分享图片

 

5.采用结对编程方式,与学习伙伴合作完成实验十编程练习2。

 

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.Scanner;


public class ss {
    public static void main(String[] args) {


        Scanner in = new Scanner(System.in);
        Calculator<Integer> sf = new Calculator<Integer>();
        File file = new File("wzt.txt");
        if(file.exists()) {
            System.out.println("文件已存在");
        }
        PrintWriter output = null;
        try {
            output = new PrintWriter(new FileOutputStream(file));
        } catch (Exception e) {
            //e.printStackTrace();
        }
        int sum = 0;
        
        System.out.println("计算结果保留两位小数");
        for (int i = 1; i < 11; i++) {
            int a = (int) Math.round(Math.random() * 100);
                int b = (int) Math.round(Math.random() * 100);
                int s = (int) Math.round(Math.random() * 3);

            
           switch(s)
           {
           case 1:
               System.out.println(i+": "+a+"/"+b+"=");
               Number c = in.nextDouble();
               output.println(a+"/"+b+"="+c);
               Number g = sf.division(a, b);
               BigDecimal division = new BigDecimal(g.doubleValue());
               g = division.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
               if (c.equals(g)) {
                   sum += 10;
                   System.out.println("恭喜答案正确");
               }
               else {
                   System.out.println("抱歉,答案错误");
               }
            
               break;
            
           case 2:
               System.out.println(i+": "+a+"*"+b+"=");
               Number c1 = in.nextDouble();
               output.println(a+"*"+b+"="+c1);
               Number g1 = sf.mulitiplication(a, b);
               BigDecimal mul = new BigDecimal(g1.doubleValue());
               g1 = mul.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
               if (c1.equals(g1) ){
                   sum += 10;
                   System.out.println("恭喜答案正确");
               }
               else {
                   System.out.println("抱歉,答案错误");
               }
               break;
           case 3:
               System.out.println(i+": "+a+"+"+b+"=");
               Number c2 = in.nextDouble();
               output.println(a+"+"+b+"="+c2);
               Number g2 =sf.addition(a, b);
               BigDecimal add = new BigDecimal(g2.doubleValue());
               g2 = add.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
               if (c2.equals(g2)) {
                   sum += 10;
                   System.out.println("恭喜答案正确");
               }
               else {
                   System.out.println("抱歉,答案错误");
               }
               
               break ;
           case 4:
               System.out.println(i+": "+a+"-"+b+"=");
               Number c3 = in.nextDouble();
               output.println(a+"-"+b+"="+c3);
               Number g3 = sf.subtraction(a, b);
               BigDecimal sub = new BigDecimal(g3.doubleValue());
               g3 = sub.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
               if (c3.equals(g3)) {
                   sum += 10;
                   System.out.println("恭喜答案正确");
               }
               else {
                   System.out.println("抱歉,答案错误");
               }
               break ;

               } 
    
          }
        System.out.println("成绩"+sum);
        output.println("成绩:"+sum);
        output.close();
        in.close();
         
    }
}

结对程序运行功能界面截图;

技术分享图片

结对过程描述,提供两人在讨论、细化和编程时的结对照片(非摆拍)。

技术分享图片

 总结 :通过这周的Java课程的学习,基本掌握了java中集合的概念,学习了集合的知识以及使用方法。实验中,运用了结对编程的方法,  通过结对编程,极大的提高了我们的编程兴趣,和编程效率,是一种很好的编程方式。

 

王志成/王之泰《面向对象程序设计(java)》第十一周学习总结

标签:generate   input   author   can   image   个数   结果   体系   教材   

原文地址:https://www.cnblogs.com/847118824wang/p/9941802.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!