zoukankan      html  css  js  c++  java
  • 《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]

  • 相关阅读:
    [JavaScript]JS由来
    [HTML5]HTML表单(Forms)
    Linux 配置SSH 无密钥登陆
    Spring Boot 的 application.properties
    Spring Boot 全局异常捕获
    Linux hostname设置,静态ip设置,hostname与静态ip相互映射
    Hadoop 集群的三种方式
    网站列表
    Hadoop -- 概念
    shell 编程
  • 原文地址:https://www.cnblogs.com/1601wyn/p/8662895.html
Copyright © 2011-2022 走看看