天天看點

《面向對象程式設計(Java)》第四周學習總結

《面向對象程式設計(Java)》第四周學習總結

實驗四類與對象的定義及使用

實驗時間2018-9-20

1、實驗目的與要求

(1) 了解使用者自定義類的定義;

類: 

類是用來描述一類事物的共性内容的, 類是抽象的;  

建立類,如何描述 屬性    功能 用變量來描述屬性 用方法來描述功能

(2) 掌握對象的聲明;

對象:  

就是現實中具體的事物,對象是具體的; 建立對象 

類名  對象名  =  new 類名(); 

如何通過對象通路類中屬性和方法呢? 對象名.變量名 對象名.方法名();

建立的對象沒有指派給具體的變量; 

是以給匿名對象的屬性指派是沒有任何意義的;  

匿名對象使用場景 1 調用方法 2 作為參數傳遞 3 添加進容器中

(3) 學會使用構造函數初始化對象;

構造函數(方法) 1.4.1 構造函數的作用  

用來給對象進行初始話的(初始化就是指給對象的各個屬性指派)  

 構造函數何時執行 

對象一建立就會調用與之相對應的構造函數

 構造函數文法 

修飾符  沒有傳回值類型  類名(參數清單){ 具體執行的代碼 } 

構造函數自動添加 

當一個類中我們沒有明确指定構造函數的話,jvm會自動幫我們添加一個空參數的構造, 

如果我們指定了,就不添加

構造函數和普通函數的差別 

5.1 執行時機不同 

對象一建立就會調用與之相對應的構造函數 普通函數隻有被調用才會執行

(4) 使用類屬性與方法的使用掌握使用;

(5) 掌握package和import語句的用途。

權限修飾符可以用來修飾兩種東西: 

Public  該類在其他包中也可以通路   (首先要導包  import) 預設

2、實驗内容和步驟

實驗1 測試以下程式,掌握檔案輸入輸出程式設計技術(檔案輸入輸出,教材61-62).

import java.io.*;

import java.util.*;

public class FileWriteReadTest {

public static void main(String[] args) throws IOException{

//寫入檔案示範

PrintWriter out = new PrintWriter("myfile.txt");

out.println("姓名 高數 Java 資料結構 平均成績 總成績");

out.println("張三 20 30 40 0 0");

out.println("李四 50 60 70 0 0");

out.close();//輸出完畢,需要close

//讀入檔案示範

Scanner in = new Scanner(new File("myfile.txt"));//為myfile.txt這個File建立一個掃描器in

int number = 1;//行号

System.out.println(in.nextLine());

while(in.hasNextLine()){//判斷掃描器是否還有下一行未讀取,該循環把檔案的每一行都讀出

String line = in.nextLine();//讀出myfile.txt的下一行

System.out.print("第"+(++number)+"行的内容: ");

Scanner linescanner = new Scanner(line);//行内容建立掃描器

linescanner.useDelimiter(" ");//使用空格作為分隔符

String name = linescanner.next();

String math = linescanner.next();

String java = linescanner.next();

String ds = linescanner.next();

String avg = linescanner.next();

String total = linescanner.next();

System.out.println("name="+name+"  math="+math+"  java="+java+"  ds="+ds+"  avg"+avg+"  total="+total);

}

in.close();//讀入完畢,最後需要對其進行close。

}

}

《面向對象程式設計(Java)》第四周學習總結

實驗2 導入第4章示例程式并測試。

測試程式1:

l 編輯、編譯、調試運作程式4-2(教材104頁);

l 結合程式運作結果,掌握類的定義與類對象的用法,并在程式代碼中添加類與對象知識應用的注釋;

l 嘗試在項目中編輯兩個類檔案(Employee.java、 EmployeeTest.java ),編譯并運作程式。

《面向對象程式設計(Java)》第四周學習總結

l 參考教材104頁EmployeeTest.java,設計StudentTest.java,定義Student類,包含name(姓名)、sex(性别)、javascore(java成績)三個字段,編寫程式,從鍵盤輸入學生人數,輸入學生資訊,并按以下表頭輸出學生資訊表:

  姓名     性别java成績

import java.util.Scanner;

public class Student implements Compare

{

    private String no;

    private String name;

    private double score;

    public Student ( String no, String name, double score )

    {

        this.no = no;

        this.name = name;

        this.score = score;

    }

    public String displays ()

    {

        StringBuilder builder = new StringBuilder ();

        builder.append ("Student [no=");

        builder.append (no);

        builder.append (", name=");

        builder.append (name);

        builder.append (", score=");

        builder.append (score);

        builder.append ("]");

        return builder.toString ();

    }

    public void setScore ( double score )

    {

        this.score = score;

    }

    public double getScore ()

    {

        return score;

    }

    @Override

    public boolean compare ( Object o )

    {

        return ( this == o || null != o && o.getClass ().equals (this.getClass ()) )

                && ( (Student) o ).score > this.score;

    }

    public static void sort ( Student[] students )

    {

        for ( int i = 0; i < students.length; i++ )

        {

            for ( int j = i + 1; j < students.length; j++ )

            {

                if (students[i].compare (students[j]))

                {

                    Student temp = students[i];

                    students[i] = students[j];

                    students[j] = temp;

                }

            }

        }

    }

    public static void main ( String[] args )

    {

        System.out.print ("建立一個含有n個學生的數組, 從鍵盤輸入n: ");

        Scanner scanner = new Scanner (System.in);

        int count = 0;

        double scores = 0;

        int n = scanner.nextInt ();

        Student[] students = new Student[n];

        System.out.println ("從鍵盤輸入每個學生的資訊: 學号、姓名、java成績 用英文逗号分隔.");

        String line = null;

        try

        {

            while (count < n && null != ( line = scanner.next () ))

            {

                if (line.matches ("^\\w+\\,\\w+\\,\\d+(\\.\\d*)?$"))

                {

                    String no = line.split ("\\,")[0].trim ();

                    String name = line.split ("\\,")[1].trim ();

                    double score = Double.parseDouble (line.split ("\\,")[2].trim ());

                    students[count] = new Student (no, name, score);

                    scores += score;

                    count++;

                }

            }

        }

        catch (ScoreException e)

        {

            e.printStackTrace ();

        }

        System.out.println ("排序:");

        sort (students);

        for ( int i = 0; i < students.length; i++ )

        {

            System.out.println (students[i].displays ());

        }

        System.out.println ("學生的java成績的平均分: " + ( scores / n ));

        scanner.close ();

        Student collegeStudent = new CollegeStudent ("001", "yugi111", 120, "1999-01-01", "man");

        System.out.println (collegeStudent.displays ());

    }

}

class CollegeStudent extends Student

{

    private String Date;

    private String sex;

    public CollegeStudent ( String no, String name, double score, String Date, String sex )

    {

        super (no, name, score);

        this.Date = Date;

        this.sex = sex;

    }

    @Override

    public String displays ()

    {

        StringBuilder builder = new StringBuilder ();

        builder.append ("CollegeStudent [Date=").append (Date).append (", sex=").append (sex).append ("]");

        return builder.toString ();

    }

}

interface Compare

{

    boolean compare ( Object o );

}

class ScoreException extends IllegalArgumentException

{

    private static final long serialVersionUID = 1L;

    public ScoreException ()

    {

        super ();

    }

    public ScoreException ( String s )

    {

        super (s);

    }

    static ScoreException forInputString ( String s )

    {

        return new ScoreException ("For input string: \"" + s + "\"");

    }

}

測試了一下之後加上了排序以及對數組長度的控制。

輸出結果如圖:

《面向對象程式設計(Java)》第四周學習總結

測試程式2:

l 編輯、編譯、調試運作程式4-3(教材116);

《面向對象程式設計(Java)》第四周學習總結

l 結合程式運作結果,了解程式代碼,掌握靜态域(netxtId)與靜态方法(getNextId)的用法,在相關代碼後添加注釋;

《面向對象程式設計(Java)》第四周學習總結
《面向對象程式設計(Java)》第四周學習總結

l 了解Java單元(類)測試的技巧。

測試程式3:

l 編輯、編譯、調試運作程式4-4(教材121);

l 結合程式運作結果,了解程式代碼,掌握掌握Java方法參數的用法,在相關代碼後添加注釋;

《面向對象程式設計(Java)》第四周學習總結

測試程式4:

l 編輯、編譯、調試運作程式4-5(教材129);

l 結合程式運作結果,了解程式代碼,掌握Java使用者自定義類的用法,掌握對象構造方法及對象使用方法,在相關代碼後添加注釋。

《面向對象程式設計(Java)》第四周學習總結

測試程式5:

l 編輯、編譯、調試運作程式4-6、4-7(教材135);

l 結合程式運作結果,了解程式代碼,掌握Java包的定義及用法,在相關代碼後添加注釋;

《面向對象程式設計(Java)》第四周學習總結

實驗3  編寫長方形類Rectangle與圓形類Circle,其中Rectangle類設定私有屬性:width,length;Circle類設定私有屬性radius。編寫Rectangle類的帶參構造函數Rectangle(int width,int length), Circle類的帶參構造函數Circle(int radius),編寫兩個類的toString方法(Eclipse可自動生成)。上述2個類均定義以下方法:

求周長的方法public int getPerimeter()

求面積的方法public int getArea()

在main方法中完成以下任務:

(1) 輸入1行長與寬,建立一個Rectangle對象;

(2) 輸入1行半徑,建立一個Circle對象;

(3) 将兩個對象的周長加總輸出,将兩個對象的面積加總輸出。

實驗代碼:

import java.util.*;

public class 實驗3 {

  public static void main(String[] args) {

         Scanner in = new Scanner(System.in);

         System.out.println("請輸入長方形的長:"); 

         int length = in.nextInt();

         System.out.println("請輸入長方形的寬:"); 

         int width = in.nextInt();

         System.out.println("請輸入圓的半徑:"); 

         double radius = in.nextDouble();

         Rectangle r=new Rectangle(length,width);

         Circle   c=new Circle(radius);

         System.out.println("矩形周長為:"+r.getPerimeter()+"矩形面積為:"+r.getArea());

         System.out.println("圓周長為:"+c.getPerimeter()+"圓面積為:"+c.getProportion());

         double d = r.getPerimeter()+c.getPerimeter();

         double e = r.getArea()+c.getProportion();

         System.out.println("長方形與圓的周長和為:"+d+"長方形與圓的面積和為:"+e);

     }

 }

class Circle {

private double radius;

public Circle(double r){

radius=r;

}

public double getPerimeter()

    {

        double Perimeter = 2*Math.PI*radius;

        return Perimeter;

    }

    public double getProportion()

    {

        double Proportion = radius*radius*Math.PI;

        return Proportion;

    }

}

class Rectangle {

private double width;

     private double length;

     public Rectangle(double w,double l)

     {

         width=w;

         length=l;

     }

     public double getPerimeter()

     {

         double Perimeter = (width+length)*2;

         return Perimeter;

     }

     public double getArea()

     {

         double Area = width*length;

         return Area;

     }

 }

輸出結果

《面向對象程式設計(Java)》第四周學習總結

對象與類學習總結:類是抽象的,而對象是具體的,類是一系列擁有相同屬性和方法的對象的抽象出來的集合。比如說“人”就是一個類,是抽象的,你并不知道這個“人”到底是誰,做什麼的,叫什麼名字,而”你的鄰居小張“就是一個對象,是實際存在的,你知道他的姓名,身高等等等等;set和get是是通路器,get用來擷取值,set用來設定值,通過将成員變量申明為private私有的以保護該成員不被所有人共享,同時封裝成屬性,即提供一個相應的public 公有的set和get方法來對該變量指派和取值,通過在該方法中添加條件來限制通路,比如一個私有成員age,在指派的時候不能随意給值,因為可以用過set方法限制給值範圍。類的概念 : 類是具有相同屬性和服務的一組對象的集合。為屬于該類的所有對象提供了統一的抽象描述,其内部包括屬性和服務兩個主要部分。在面向對象的程式設計語言中,類是一個獨立的程式機關,應該有一個類名并包括屬性說明和服務說明兩個主要部分。

對象的概念:對象是系統中用來描述客觀事物的一個實體,是構成系統的一個基本機關。一個對象由一組屬性和對這組屬性進行操作的一組服務組成。從更抽象的角度來說,對象是問題域或實作域中某些事物的一個抽象,它反映該事物在系統中需要儲存的資訊和發揮的作用;它是一組屬性和有權對這些屬性進行操作的一組服務的封裝體。客觀世界是由對象和對象之間的聯系組成的。

此外,在輸入代碼的過程中還是要注意細節問題,例如中英文的切換等等,句末的分号等等,注意培養良好的程式設計習慣。

posted on 2018-09-24 14:26  Fairber 閱讀( ...) 評論( ...) 編輯 收藏

轉載于:https://www.cnblogs.com/fairber/p/9693049.html