1. 程式人生 > >實驗10窮吉201771010119

實驗10窮吉201771010119

實驗十  泛型程式設計技術

 

理論知識:

泛型也稱為引數化型別,就是在定義類、方法、介面時,通過型別引數指示將要處理的物件型別。

.泛型程式設計:編寫程式碼可以被很多不同型別的物件所重用。

.一個泛型類就是具有一個或多個型別變數的類,即建立用型別作為引數的類。

.Pair類引入了一個型別變數T,用尖括號(<>)括起來,並放在類名的後面。泛型類可以有多個型別變數。

.類定義中的型別變數用於指定方法的返回型別以及域、區域性變數的型別。

.除了泛型類外,還可以只單獨定義一個方法作為泛型方法,用於指定方法引數或者返回值為泛型型別,留待方法呼叫時確定。泛型方法可以宣告在泛型類中,也可以宣告在普通類中。

泛型變數上界:extends關鍵字所宣告的上界既可以是一個類,也可以是一個介面。

.一個型別變數或萬用字元可以有多個限定,限定型別用“&”分割。

.泛型變數下界:通過使用super關鍵字可以固定泛型引數的型別為某種型別或者其超類。當程式希望為一個方法的引數限定型別時,通常可以使用下限萬用字元。

.Java中的陣列是協變的。例如:Integer擴充套件了Number,那麼在要求Number[]的地方完全可以傳遞或者賦予Integer[],Number[]也是Integer[]的超型別。Employee 是Manager 的超類, 因此可以將一個Manager[]陣列賦給一個型別為Employee[]的變數。

注:泛型型別的陣列不是協變的。

1、實驗目的與要求

(1) 理解泛型概念;

(2) 掌握泛型類的定義與使用;

(3) 掌握泛型方法的宣告與使用;

(4) 掌握泛型介面的定義與實現;

(5)瞭解泛型程式設計,理解其用途。

2、實驗內容和步驟

實驗1: 匯入第8章示例程式,測試程式並進行程式碼註釋。

測試程式1:

編輯、除錯、執行教材311、312頁 程式碼,結合程式執行結果理解程式;

在泛型類定義及使用程式碼處添加註釋;

掌握泛型類的定義及使用。

package pair1;

/**
* @version 1.01 2012-01-26
* @author Cay Horstmann
*/
public class PairTest1
{
public static void main(String[] args)
{
String[] words = { "Mary", "had", "a", "little", "lamb" };
Pair<String> mm = ArrayAlg.minmax(words);
System.out.println("min = " + mm.getFirst());
System.out.println("max = " + mm.getSecond());
}
}

class ArrayAlg
{
/**
* Gets the minimum and maximum of an array of strings.
* @param a an array of strings
* @return a pair with the min and max value, or null if a is null or empty
*/
public static Pair<String> minmax(String[] a)
{
if (a == null || a.length == 0) return null;
String min = a[0];
String max = a[0];
for (int i = 1; i < a.length; i++)
{
if (min.compareTo(a[i]) > 0) min = a[i];
if (max.compareTo(a[i]) < 0) max = a[i];
}
return new Pair<>(min, max);
}
}

結果圖:

 

測試程式2:

編輯、除錯執行教材315 PairTest2,結合程式執行結果理解程式;

在泛型程式設計程式碼處新增相關注釋;

掌握泛型方法、泛型變數限定的定義及用途。

package pair2;

import java.time.*;

/**
* @version 1.02 2015-06-21
* @author Cay Horstmann
*/
public class PairTest2
{
public static void main(String[] args)
{
LocalDate[] birthdays =
{
LocalDate.of(1906, 12, 9), // G. Hopper
LocalDate.of(1815, 12, 10), // A. Lovelace
LocalDate.of(1903, 12, 3), // J. von Neumann
LocalDate.of(1910, 6, 22), // K. Zuse
};
Pair<LocalDate> mm = ArrayAlg.minmax(birthdays);
System.out.println("min = " + mm.getFirst());
System.out.println("max = " + mm.getSecond());
}
}

class ArrayAlg
{
/**
Gets the minimum and maximum of an array of objects of type T.
@param a an array of objects of type T
@return a pair with the min and max value, or null if a is
null or empty
*/
public static <T extends Comparable> Pair<T> minmax(T[] a)
{
if (a == null || a.length == 0) return null;
T min = a[0];
T max = a[0];
for (int i = 1; i < a.length; i++)
{
if (min.compareTo(a[i]) > 0) min = a[i];
if (max.compareTo(a[i]) < 0) max = a[i];
}
return new Pair<>(min, max);
}
}

結果圖:

測試程式3:

用除錯執行教材335 PairTest3,結合程式執行結果理解程式;

瞭解萬用字元型別的定義及用途。

package pair3;

/**
* @version 1.01 2012-01-26
* @author Cay Horstmann
*/
public class PairTest3
{
public static void main(String[] args)
{
Manager ceo = new Manager("Gus Greedy", 800000, 2003, 12, 15);
Manager cfo = new Manager("Sid Sneaky", 600000, 2003, 12, 15);
Pair<Manager> buddies = new Pair<>(ceo, cfo);
printBuddies(buddies);

ceo.setBonus(1000000);
cfo.setBonus(500000);
Manager[] managers = { ceo, cfo };

Pair<Employee> result = new Pair<>();
minmaxBonus(managers, result);
System.out.println("first: " + result.getFirst().getName()
+ ", second: " + result.getSecond().getName());
maxminBonus(managers, result);
System.out.println("first: " + result.getFirst().getName()
+ ", second: " + result.getSecond().getName());
}

public static void printBuddies(Pair<? extends Employee> p)
{
Employee first = p.getFirst();
Employee second = p.getSecond();
System.out.println(first.getName() + " and " + second.getName() + " are buddies.");
}

public static void minmaxBonus(Manager[] a, Pair<? super Manager> result)
{
if (a.length == 0) return;
Manager min = a[0];
Manager max = a[0];
for (int i = 1; i < a.length; i++)
{
if (min.getBonus() > a[i].getBonus()) min = a[i];
if (max.getBonus() < a[i].getBonus()) max = a[i];
}
result.setFirst(min);
result.setSecond(max);
}

public static void maxminBonus(Manager[] a, Pair<? super Manager> result)
{
minmaxBonus(a, result);
PairAlg.swapHelper(result); // OK--swapHelper captures wildcard type
}
// Can't write public static <T super manager> ...
}

class PairAlg
{
public static boolean hasNulls(Pair<?> p)
{
return p.getFirst() == null || p.getSecond() == null;
}

public static void swap(Pair<?> p) { swapHelper(p); }

public static <T> void swapHelper(Pair<T> p)
{
T t = p.getFirst();
p.setFirst(p.getSecond());
p.setSecond(t);
}
}

結果圖:

實驗2:程式設計練習:

程式設計練習1:實驗九程式設計題總結

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 }
實驗中主類是:class test
子類:class Student
在實驗中進行寫程式碼時有時候不知道怎麼去定義這個程式碼,怎樣把想的東西用程式碼表示;
缺少練習,檔案的讀取上也有一些問題。

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;

}

主類:demo

在這個實驗中在最後進行執行時出現0時在不執行的問題還沒解決;

程式設計練習2:採用泛型程式設計技術改進實驗九程式設計練習2,使之可處理實數四則運算,其他要求不變。

package 運算;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

public class Demo {
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();
}
}
}

 

 

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

}

結果圖:

實驗總結:在這次實驗裡把自己在實驗中的遇到的問題都闡述了一遍,在進行了新的程式設計練習。