《java第二次實驗》
(一)學習總結
1.什麽是構造方法?什麽是構造方法的重載?下面的程序是否可以通過編譯?為什麽?
public class Test {
public static void main(String args[]) {
Foo obj = new Foo();
}
}
class Foo{
int value;
public Foo(int intValue){
value = intValue;
}
}
構造方法是一種特殊的方法,它是一個與類同名且沒有返回值類型的方法。對象的創建就是通過構造方法來完成,其功能主要是完成對象的初始化。當類實例化一個對象時會自動調用構造方法。構造方法和其他方法一樣也可以重載。
(1)在Java中,允許在一個類中定義多個構造方法。
(2)在創建對象時,系統會自動根據所調用的構造方法中包含的參數類型,個數,選擇匹配的構造方法創建對象。
(3)構造方法的註意事項
(4)如果在類中沒有明確定義構造方法,系統會自動調用默認的構造方法。
(5)如果指定了構造方法,則不調用默認的構造方法。
(6)如果已經指定了有參的構造方法,而又要調用無參的構造方法,則要在類中追加無參構造。
下面的程序不能通過編譯,new Foo()錯誤,應創建構造函數Foo()。
2.運行下列程序,結果是什麽?分析原因,應如何修改
public class Test {
public static void main(String[] args) {
MyClass[] arr=new MyClass[3];
arr[1].value=100;
}
}
class MyClass{
public int value=1;
}
數組沒有正常初始化,程序只是對arr數組進行了聲明,並沒有初始化。
修改為:
public class Test {
public static void main(String[] args) {
MyClass[] arr=new MyClass[3];
for(int i=0;i<3 ;i++){
arr[i]=new MyClass();
}
arr[1].value=100;
}
}
class MyClass{
public int value=1;
}
3.運行下列程序,結果是什麽?說明原因。
public class Test {
public static void main(String[] args) {
Foo obj1 = new Foo();
Foo obj2 = new Foo();
System.out.println(obj1 == obj2);
}
}
class Foo{
int value = 100;
}
結果是false,比較的是地址
4.什麽是面向對象的封裝性,Java中是如何實現封裝性的?試舉例說明。
封裝就是把屬性和方法捆綁到一起,封裝到一個對象中去,形成一個不可分割的獨立單位,修改屬性的可見性來限制對屬性的訪問,並為每個屬性創建一對取值方法和賦值方法,用於對這些屬性的訪問。通過封裝,可以實現對屬性的數據訪問限制,同時增加了程序的可維護性。
public class Worker {
private int no;
private Datet bir,sta;
private String name,sex;
private Home whome;
}
public Worker(String name,String sex,int no,Datet bir,Datet sta) {
this.name=name; this.sex=sex; this.no=no; this.bir=bir; this.sta=sta;
}
public void setbir(Datet bir){
this.bir=bir;
}
public void setsta(Datet sta){
sta=sta;
}
5.閱讀下面程序,分析是否能編譯通過?如果不能,說明原因。
class A{
private int secret = 5;
}
public class Test{
public static void main(String args[]){
A a = new A();
System.out.println(a.secret++);
}
}
不能,在A定義中對secret進行了封裝,在主類函數內無法直接對secret進行操作。可以利用get set 方法,或者將secret變為 public屬性。
public class Test{
int x = 50;
static int y = 200;
public static void method(){
System.out.println(x+y);
}
public static void main(String args[]){
Test.method();
}
}
不能正確編譯通過,因為沒有定義類型為 Test 的對象,Test.method();應該在前面定義一個Test 對象,先在Test的定義裏寫出定義方法 比如
6.使用類的靜態變量和構造方法,可以跟蹤某個類創建的對象個數。聲明一個圖書類,數據成員為編號,書名,書價,並擁有靜態數據成員冊數記錄圖書的總數。圖書編號從1000開始,每產生一個對象,則編號自動遞增(利用靜態變量和構造方法實現)。下面給出測試類代碼和Book類的部分代碼,將代碼補充完整。
class Book{
int bookId;
String bookName;
double price;
static int count=1000;
public Book(String bookName, double price) {
this.bookName = bookName;
this.price = price;
}
public int getbookId(){
return bookId;
}
public void setbookId(int bookId){
this.bookId=bookId;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Book() {
count++;
}
public String toString(){
return "圖書編號:"+this.bookId+"書名:"+this.bookName+"書價:"+this.price+"產生對象個數:"+count;
}
}
public class Test{
public static void main(String args[]){
Book[] books = {new Book("c語言程序設計",29.3),
new Book("數據庫原理",30),
new Book("Java學習筆記",68)};
System.out.println("圖書總數為:"+"count");
for(Book book:books){
System.out.println(book.toString());
}
}
}
7.什麽是單例設計模式?它具有什麽特點?用單例設計模式設計一個太陽類Sun。
一個類有且僅有一個實例,並且自行實例化向整個系統提供,實例控制:單例模式會阻止其他對象實例化其自己的單例對象的副本,從而確保所有對象都訪問唯一實例。靈活性:因為類控制了實例化過程,所以類可以靈活更改實例化過程。節約內存性。缺點是:可能無法訪問庫源代碼,所以可能會意外發現自己無法直接實例化此類。
代碼如下:
public class Sun {
private static Sun instance = null;
private Sun() {
}
public synchronized static Sun getInstance() {
if (instance == null) {
instance = new Sun();
}
return instance;
}
}
8.理解Java參數傳遞機制,閱讀下面的程序,運行結果是什麽?說明理由。
public class Test {
String str = new String("你好 ");
char[] ch = { ‘w‘,‘o‘,‘l‘,‘l‘,‘d‘ };
public static void main(String args[]) {
Test test = new Test();
test.change(test.str, test.ch);
System.out.print(test.str);
System.out.print(test.ch);
}
public void change(String str, char ch[]) {
str = "hello";
ch[0] = ‘W‘;
}
}
你好wolld
9.總結
(1)面向對象
類的定義和實例化調用,重載
重寫類成員和實例成員的區別
簡單類的設計
掌握String類的常用方法
繼承的實現方法
成員變量的繼承和隱藏
(2)面向對象高級
多態性
轉型
接口和抽象類(概念)
利用接口進行排序
(二)實驗總結
1.用面向對象思想完成評分系統
import java.util.Scanner;
import java.util.Arrays;
class Judges {
Scanner in=new Scanner(System.in);
private int judgeer;
private double[] score;
public Judges(){
}
public Judges(int number){
this.judgeer=number;
}
public void setJudgeer(int judgeer){
this.judgeer=judgeer;
}
public void setScore(double[] score){
this.score=score;
}
public int getJudgeer(){
return this.judgeer;
}
public double[] getScore(){
return this.score;
}
public void inputScore(){
score = new double[judgeer];//在輸入時進行實例化
for(int j=0;j<judgeer;j++){
score[j]=in.nextDouble();
}
/*for(int i=0;i<judgeer;i++){
System.out.println(score[i]);
}*/
//System.out.println("inputScore"+score);
}
public void maxMin(double[] score){
//System.out.println("maxMin"+score);
Arrays.sort(score);
System.out.println("去掉一個最低分:"+score[0]);
System.out.println("去掉一個最高分:"+score[judgeer-1]);
}
public double average(double[] score){
//Arrays.sort(score);
double sum=0;
for(int k=1;k<judgeer-1;k++){
sum=sum+score[k];
}
sum=sum/(judgeer-2);
//System.out.println("average"+score);
return sum;
}
}
class Player implements Comparable<Player>{
private String name;//姓名
private int number;//編號
private double score;//得分
public Player(){
}
public Player(int number,String name){
this.name=name;
this.number=number;
this.score=score;
}
public void setName (String name){//setname
this.name=name;
}
public void setNumber(int number){//setnumber
this.number=number;
}
public void setScore(double score){//setscore
this.score=score;
}
public String getName(){//getname
return this.name;
}
public int getNumber(){//getnumber
return this.number;
}
public double getScore(){//getscore
return this.score;
}
public String toString(){
return "編號:"+number+","+"姓名:"+name+","+"分數"+score+":";
}
public int compareTo(Player o){
if(this.score>o.score){
return -1;
}
else if(this.score<o.score){
return 1;
}
else{
return 0;
}
}
}
import java.util.Arrays;
import java.util.Scanner;
public class Score {
public static void main(String[] args){
Scanner in=new Scanner(System.in);
int numberplay,numberjudge;
System.out.println("輸入選手人數");
numberplay=in.nextInt();
Player[] play=new Player[numberplay];
//Player plays=new Player();
System.out.println("輸入評委人數");
numberjudge=in.nextInt();
Judges judge=new Judges(numberjudge);
for(int i=0;i<numberplay;i++){
System.out.println("輸入選手編號和姓名");
play[i]=new Player(in.nextInt(),in.next());
System.out.println("輸入成績:");
judge.inputScore();//輸入成績
double[] a=judge.getScore();
//System.out.println("a"+a);
judge.maxMin(a);
double score=judge.average(a);
System.out.println("總成績為:"+score);
play[i].setScore(score);
}
Arrays.sort(play);
for(int i=0;i<numberplay;i++){
System.out.println(play[i].toString());
}
}
}
2.Email驗證
import java.util.Scanner;
public class DZ {
public static void main(String [] args){
System.out.print("請輸入電子郵件地址:");
Scanner sc=new Scanner(System.in);
String str=sc.next();
int first=str.indexOf(‘@‘);
int first1=str.indexOf(‘.‘);
int last=str.lastIndexOf(‘.‘);
if(first<1||first1<1||first>first1||(last==str.length()-1)){
System.out.println(str+"這是一個不合格的地址");
}
else if(first1-first>1){
System.out.println(str+"這是一個合格的地址");
}
else{
System.out.println(str+"這是一個不合格的地址");
}
}
}
3.查找子串
public class CZ {
public static void main(String [] args){
String s ="abcbcaadbca";
String s1=s;//不改變原字符串
int count=0;
while(s1.indexOf("bc")!=-1){
int index=s1.indexOf("bc");
count++;
s1=s1.substring(index+2);//返回字符串從index+2開始到字符串
}
System.out.println(count);
System.out.println(s);
}
}
4.統計文件
import java.util.Scanner;
public class Files {
public static void main(String[] args) {
System.out.println("請輸入一串文件名,文件名之間用‘,’隔開:");
Scanner in=new Scanner(System.in);
String str=in.nextLine();
String s[]=str.split(",");//字符串分割
for(int i=0;i<s.length;i++)
{
char []a=s[i].toCharArray();//文件變成字符數組
if(a[0]>=97 && a[0]<=122)
a[0]=(char)(a[0]-32);//如果文件的首字母不是大寫,將其變成大寫
s[i]=new String(a);//字符數組變成字符串
System.out.println(s[i]);
}
//String a=new String();
for(int i=0;i<s.length;i++)
{
int n=0;
int num=s[i].indexOf(".");//找到後綴名
String str1=s[i].substring(num);
//if(a.indexOf(str1)<0)
//{
//a=a+str1;
for(int j=i;j<s.length;j++)//查找文件
{
//int num2=s[j].indexOf(".");
//String x=s[j].substring(num2);
if(/*str1.equals(x)*/s[j].indexOf(str1)!=-1)//文件類型相同
{
n++;
}
}
System.out.println(str1.substring(1)+"文件有"+n+"個");
//}
}
}
}
5.類的設計
public class Time {
private int year;
private int month;
private int day;
private String birthday;
public String worktime;
private Employee emp;//生日和參加工作時間應屬於員工的屬性
public void setYear(int year){
this.year=year;
}
public int getYear(){
return this.year;
}
public void setMonth(int month){
this.month=month;
}
public int getMonth(){
return this.month;
}
public void setDay(int day){
this.day=day;
}
public int getDay(){
return this.day;
}
public Time(){
}
public Time(int year1,int month1,int day1,int year2,int month2,int day2){//構造方法
birthday=year1+"-"+month1+"-"+day1;
worktime=year2+"-"+month2+"-"+day2;
}
public void setBirthday(int year,int month,int day){
this.birthday=year+"-"+month+"-"+day;
}
public String getBirthday(){
return birthday;
}
public void setWorktime(int year,int month,int day){
this.worktime=year+"-"+month+"-"+day;
}
public String getWorktime(){
return worktime;
}
public Time(int year,int month,int day){//構造方法
this.year=year;
this.month=month;
this.day=day;
}
/*public String birthday(){
return year+"-"+month+"-"+day;
}
public String worktime(){
return year+"-"+month+"-"+day;
}
}
(三)代碼托管[https://gitee.com/hebau_java_cs16/Java_CS01-wyn/tree/master/ex02]
《java第二次實驗》