<<java 技术>>第二次作业

(一)学习总结

-1.什么是构造方法?什么是构造方法的重载?下面的程序是否可以通过编译?为什么?
构造方法:它是一个与类同名且返回值类型为同名类型的方法。构造方法用于在创建对象时对其进行初始化。
- Person per = new Person() ;
-特点:
-①方法名与类名相同;
-②方法名前没有返回值类型的声明,方法中不能使用return语句返回一个值;
-③用户不能直接调用,而是通过关键字new自动调用
?? -④在构造方法的实现中,也可以进行方法重载
-构造方法的重载:就是方法名称相同,但参数的类型和参数的个数不同,通过传递参数的个数及类型不同以完成不同功能的方法调用。

public class Test {
public static void main(String args[]) {
Foo obj = new Foo();
}
}
class Foo{
int value;
public Foo(int intValue){
value = intValue;
}
}
-不能通过编译。类中定义的是一个有参的构造函数,而测试类用的是无参的。
-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;
}
-结果:Exception in thread "main" java.lang.NullPointerException
at Test1.main(Test1.java:4)
-原因:没有对对象进行实例化,数组里每一个对象都是null。
-修改:对数组里的数通过new构造方法进行实例化。
-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
-原因:obj1和obj2代表的是地址,而不是值。
-4.什么是面向对象的封装性,Java中是如何实现封装性的?试举例说明。
封装把对象的所有组成部分(数据和方法)封装在一起构成类。
对象本身的数据得到保护/隐藏
其他对象通过该对象的访问方法(接口/interface)与之发生联系。
好处
模块化
信息隐藏--通常定义一个公共接口/方法实现对对象的访问。
要对数据进行封装,通常用关键字private声明属性
在JAVA开发的标准规定中,封装属性的设置和取得依靠setter及getter方法完成

setter:设置属性的值

public void setBalance(int balance) {

this.balance = balance;

}

getter:调用该属性的值

public int getBalance() {

return balance;

}
-5.阅读下面程序,分析是否能编译通过?如果不能,说明原因。
(1)

class A{
private int secret = 5;
}
public class Test{
public static void main(String args[]){
A a = new A();
System.out.println(a.secret++);
}
}
-不能,因为secret是A的私有属性,不能直接调用。
(2)

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();
}
}
-不能,因为x没有用static申明,所以method方法中不能调用x.
-6.使用类的静态变量和构造方法,可以跟踪某个类创建的对象个数。声明一个图书类,数据成员为编号,书名,书价,并拥有静态数据成员册数记录图书的总数。图书编号从1000开始,每产生一个对象,则编号自动递增(利用静态变量和构造方法实现)。下面给出测试类代码和Book类的部分代码,将代码补充完整。

class Book{
int bookId;
String bookName;
double price;
public static int sum;
static {
sum=10;
}
public Book(String bookName,double price) {
this.bookName=bookName;
this.price=price;
this.bookId=sum;
sum++;
}
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 static int totalBook() {

	return sum;
}
public String toString() {
	return "编号:"+ bookId+"书名:"+bookName+"书的价格:"+price+"图书总册数:"+sum;
}
//重写toString方法

}
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("图书总数为:"+ Book.totalBook());
for(Book book:books){
System.out.println(book.toString());
}
}
}

-7.什么是单例设计模式?它具有什么特点?用单例设计模式设计一个太阳类Sun。
-单例模式,是一种常用的软件设计模式。在它的核心结构中只包含一个被称为单例的特殊类。通过单例模式可以保证系统中,应用该模式的类一个类只有一个实例。即一个类只有一个对象实例
public class Sun{
private static Sun instance=null;
public static Sun getInstance(){
return instance;
}
private Sun(){
}
}

-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';
}
}
-结果:你好 world
-str是引用类型,用change类型传过来后,释放地址空间,没有改变str中的值,ch是数组,用change方法改变了数组的第一个元素,在通过change方法返回原函数使用。

-9.其他需要总结的内容。

(二)实验总结

本次实验包括实验二和实验三两次的内容:
-1.用面向对象思想完成评分系统
程序设计思路:构造选手类和评委类,在类中写出每个对象的set和get方法,再在类中写Stringto方法,在测试类调用这些方法。
问题1:找最大值和最小值时,输出的值不对
原因:符号搞反了
解决方案:最大值因该是score[i]>score[0]最小值因该是score[i]<score[0]
问题2:测试类get方法的调用
原因:刚开始还不太会用get方法
问题3: public int compareTo函数不知道用来比较那几个

import java.util.Scanner;
import java.awt.print.Paper;
import java.util.Arrays;
public class Person {

public static void main(String[] args) {
	double a;
	String no,na;
	System.out.println("输入选手数");
	Scanner input=new Scanner(System.in);
	int xnum=input.nextInt();//输入选手人数
	Player []people=new Player[xnum];
	System.out.println("输入评委数");
	int pnum=input.nextInt();//输入评委人数
	for(int i = 0; i < xnum;i++){
	       System.out.println("输入选手编号");
	       no=input.next();
	       System.out.println("输入选手姓名");
	       na=input.next();
	       System.out.println("请为"+na+"号选手打分:");
	       judge grade=new judge(pnum); 
	       grade.inputscore();
	       a=grade.average(); 
	       System.out.printf(na+"号选手的最后得分:%.2f
",(float)a);
	       people[i]=new Player(na,no,a);
		}
		Arrays.sort(people);
		System.out.println("排行榜"+"	");
		for(int i=0;i<xnum;i++){
			System.out.println(people[i].toString());
		}
	       
	}

}

public class Player implements Comparable{
private String num;
private String name;
private double score;

	public Player(String name, String num,double score) {
		this.name = name;
		this.num = num;
		this.score = score;
	}
	public String getname(){
		return name;
	}
	public void setname(String n){
		this.name = n;
	}
	public String getnum() {
		return num; // 取得编号
	}

	public void setnum(String m){ 

		this.num = m;
	}

	public double getscore() {
		return score;
	}

	public void setscore(double s) {
		this.score = s;
	}

	public String toString(){
		return "编号:"+this.getnum()+"姓名:"+this.getname()+"得分:"+this.getscore() ;
	}
	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.Scanner;
import java.util.Arrays;
public class judge {
private int pnum;//评委人数
double score[]=null;//评委给出的分数
public judge(){

}
public judge(int people){
	pnum = people;
}
public void setpnum(int pnum){
	this.pnum=pnum;
}
public int getjpnum(){
	return pnum;
}
public void setpnum(double[] score){
	this.score =score;
}
public double[] getscore(){
	return score;
}
public void inputscore() {
	Scanner input=new Scanner(System.in);
	double score[]=new double[pnum];
	for(int i=0;i<this.pnum;i++){                                                                  
		score[i]=input.nextDouble();
		this.score=score;
	}
}
public double average(){
		double max=score[0],min=score[0],sum=0,ave;
		for(int i=0;i<pnum;i++) {
			
			if(score[i]>score[0]) {
				max=score[i];
			}
			if(score[i]<score[0]) {
				min=score[i];
				}
			sum+=score[i];
		}
		System.out.println("去掉一个最高分:"+max);
		System.out.println("去掉一个最低分:"+min);
		ave=(sum-max-min)/(double)(pnum-2);
		return ave;
	}

}

2.Email验证
程序设计思路:输入的邮箱需进行查找@和.的位置,还需要判断@和.的位置和以com|cn|net|gov|edu|org结尾。
问题1:把@和.的位置判断和判断以com|cn|net|gov|edu|org结尾放到了一起,不能反回true。
原因:接收的函数的变量定义的是int型
解决方案:改成boolean型

import java.util.Scanner;
public class Email {

public static void main(String[] args) {
	System.out.println("请输入邮箱地址");
	Scanner input=new Scanner(System.in);
	String str=input.next();
	boolean no=address(str);
	if(no==true) {
		System.out.println("email地址正确");
	}
	else{
		System.out.println("email地址不正确");
	}
	
}
public static boolean address(String str){
	int first,last ;
	first=str.indexOf("@");
	last=str.indexOf(".");
	if((first!=-1&&last!=-1)&&(first<last)&&!(str.startsWith("@"))&&(str.endsWith("com")||str.endsWith("cn")||str.endsWith("net")||str.endsWith("gov")||str.endsWith("edu")||str.endsWith("org"))){
		return true;
	}
	return false;
}

}

3.查找子串
程序设计思路:将字符串转化成字符数组,再比较
问题1:不知道怎么写
原因:不知道怎么比较
解决方案:听别人讲的
问题2:在循环里写的i的增量我觉得应该是加上b数组的长度,可是不对,而且在比较时不明白为什么用a[i]=b[0]来判断

import java.util.Scanner;
public class Zifu {
public static void main(String[] args) {
System.out.println("请输入一串字符串");
Scanner input=new Scanner(System.in);
String no=input.next();
System.out.println("请输入指定字符串");
String num=input.next();
System.out.println(find(no,num));
}
public static int find(String no,String num){
int sum=0;
char a[]=no.toCharArray();
char b[]=num.toCharArray();
if(no.contains(num)) {
for(int i=0;i<a.length;i++) {
if(a[i]==b[0]) {
sum++;
}
}
}
return sum;
}
}

4.统计文件
程序设计思路:输入的字符串通过,来拆分
问题1:不会把首字符变成大写
原因:不能准确的理解函数,运用函数。
解决方案:问的别人
问题2:输出的时候越界了
原因:输出的时候s[x].substring(1,s[x].length()写的是s[x].substring(1,s[x].(length-1)()
解决方案:输出的时候因该是s[x].substring(1,s[x].length()

import java.util.Scanner;
public class colect {

public static void main(String[] args) {
	System.out.println("请输入一串字符串");
	Scanner input=new Scanner(System.in);
	String no=input.next(); 
    num(no);
}
public static void num(String no){ 
	int a=0,b=0,c=0;
	 String s[] = no.split("\,") ; 
        for(int x=0;x<s.length;x++){ 
          
             if(s[x].endsWith(".java")){
            	 a++;
             }
             if(s[x].endsWith(".cpp")){
            	 b++;
             }
             if(s[x].endsWith(".txt")){
            	 c++;
             }
             String n=s[x].substring(0,1);
             System.out.println(n.toUpperCase()+s[x].substring(1,s[x].length()));
            
       }
        System.out.println(".java出现的次数为:"+a); 
        System.out.println(".cpp出现的次数为:"+b);
        System.out.println(".txt出现的次数为:"+c);
        
        
}

}

5.类的设计

程序设计思路:构造日期类和职工类和部门类,在类中写出每个对象的set和get方法,再在类中写Stringto方法,在测试类调用这些方法。
问题1:出现空指针
原因:没有设置关系
解决方案:在测试中设置关系
问题2:输出的时候因为在类中定义的类型不同,调用的时候老出错。
原因:调用查找部门经理时没有调用职工类的getdepartment()方法
解决方案:像调用查找部门经理时先调用职工类的getdepartment()在调用部门类的getmanger()最后在调用toString()方法

public class Test {
public static void main(String[] args) {
Worker w[]={new Worker("0001","王五","男"),
new Worker("0002","赵六","男"),
new Worker("0003","王红","女"),
new Worker("0004","钱三","男"),
new Worker("0005","孙子","男"),
new Worker("0006","柳柳","女"),
new Worker("0007","吴倩","女"),
new Worker("0008","周四","男"),
new Worker("0009","张倩","女"),
new Worker("0010","孙悦","女")
};
Time birthday[]={new Time("1988","01","20"),
new Time("1970","05","18"),
new Time("1968","10","24"),
new Time("1974","07","25"),
new Time("1983","04","20"),
new Time("1976","06","18"),
new Time("1978","01","14"),
new Time("1957","06","24"),
new Time("1987","01","02"),
new Time("1960","02","07")
};

	Time worktime[]={new Time("2008","10","20"),
			new Time("1990","07","18"),
			new Time("1990","01","24"),
			new Time("1996","03","02"),
			new Time("2005","04","04"),
			new Time("2000","06","18"),
			new Time("1999","10","14"),
			new Time("1988","04","04"),
			new Time("2015","10","02"),
			new Time("1996","02","17")
	};
	for(int i=0;i<10;i++){
		w[i].setbirthday(birthday[i]);
	}
	for(int i=0;i<10;i++){
		w[i].setwtime(worktime[i]);
	}
	section d1=new section("1","技术部");
	section d2=new section("2","工程部");
	d1.setnum(new Worker[] {w[0],w[1],w[5],w[7],w[8]});
	d2.setnum(new Worker[] {w[2],w[3],w[4],w[6],w[9]});
	d1.setmanger(w[3]);
	d2.setmanger(w[8]);
	w[0].setdepartment(d1);
	w[1].setdepartment(d1);
	w[2].setdepartment(d2);
	w[3].setdepartment(d2);
	w[4].setdepartment(d2);
	w[5].setdepartment(d1);
	w[6].setdepartment(d2);
	w[7].setdepartment(d1);
	w[8].setdepartment(d1);
	w[9].setdepartment(d2);
	for(int i=0;i<10;i++){
		System.out.printf(w[i].toString());
		System.out.printf("    ");
		System.out.printf("生日:");
		System.out.printf(birthday[i].toString());
		System.out.printf("    ");
		System.out.printf("工作时间:");
		System.out.printf(worktime[i].toString());
		System.out.printf("    ");
		System.out.println("所在部门:  "+w[i].getdepartment().toString());
		System.out.println(w[i].getname()+"的部门经理:"+w[i].getdepartment().getmanger().toString());
		System.out.printf("
");
	}
		System.out.printf("
");
		System.out.printf( d1+"	"+"部门经理:"+w[3].getdepartment().getmanger().toString()+"
"+"员工:" );
		System.out.printf("
");
		for(int i=0;i<d1.getnum().length;i++) {
			System.out.printf(d1.getnum()[i].toString()	);
			System.out.printf("    ");
			System.out.printf("生日:");
			System.out.printf(birthday[i].toString());
			System.out.printf("    ");
			System.out.printf("工作时间:");
			System.out.printf(worktime[i].toString());
			System.out.printf("    ");
			System.out.printf("
");
		}
		System.out.printf("
");
		System.out.printf( d2+"	"+"部门经理:"+w[8].getdepartment().getmanger().toString()+"
"+"员工:" );
		System.out.printf("
");
		for(int i=0;i<d2.getnum().length;i++) {
			System.out.printf(d2.getnum()[i].toString()	);
			System.out.printf("    ");
			System.out.printf("生日:");
			System.out.printf(birthday[i].toString());
			System.out.printf("    ");
			System.out.printf("工作时间:");
			System.out.printf(worktime[i].toString());
			System.out.printf("    ");
			System.out.printf("
");
		}		
}

}

class Time{
private String day;
private String month;
private String year;
private Worker worker;

	public Time(String year,String month,String day) {
		this.day = day;
		this.month = month;
		this.year = year;
	}
	public String getday(){
		return day;
	}
	public void setday(String d){
		this.day = d;
	}
	public String getmonth() {
		return month; 
	}

	public void setmonth(String m){ 
		this.month = m;
	}
	public Worker getworker() {
		return worker; 
	}

	public void setworker(Worker w){ 
		this.worker = w;
	}

	public String getyear() {
		return year;
	}

	public void setyear(String y) {
		this.year = y;
	}

	public String toString(){
		return this.year+"-" +this.month+"-"+this.day;
	}

}

class Worker {
private String num;
private String name;
private String sex;
private Time birthday;
private section department;
private Time wtime;

	public Worker(String num, String name,String sex) {
		this.num = num;
		this.name = name;
		this.sex = sex;
		}
	public String getname(){
		return name;
	}
	public void setname(String na){
		this.name = na;
	}
	public String getnum() {
		return num; 
	}

	public void setnum(String nu){ 

		this.num = nu;
	}

	public String getsex() {
		return sex;
	}

	public void setsex(String se) {
		this.sex = se;
	}
	public Time getbirthday() {
		return birthday;
	}

	public void setbirthday(Time bi){ 

		this.birthday = bi;
	}
	public section getdepartment() {
		return department;
	}

	public void setdepartment(section de) {
		this.department = de;
	}
	public Time getwtime(){
		return wtime;
	}
	public void setwtime(Time wt){
		this.wtime = wt;
	}

	public String toString(){
		return "职工号:"+this.getnum()+"    "+"姓名:"+this.getname()+"    "+"性别:"+this.getsex();
		
	}

}

class section {
private String sno;
private String sname;
private Worker manger;
private Worker num[];
public section(String sno,String sname) {
this.sno = sno;
this.sname = sname;
}
public String getsno(){
return sno;
}
public void setsno(String sn){
this.sno = sn;
}
public String getsname() {
return sname;
}

	public void setsname(String sna){ 
		this.sname = sna;
	}
	public Worker getmanger() {
		return manger;
	}

	public void setmanger(Worker ma) {
		this.manger = ma;
	}
	public Worker[] getnum() {
		return num;
	}

	public void setnum(Worker[] nm) {
		this.num =nm;
	}
	public String toString(){
		return "部门编号:"+this.getsno()+"	"+"部门名称:"+this.getsname();
	}

}


https://gitee.com/hebau_java_cs16/Java_CS01lzt

原文地址:https://www.cnblogs.com/1998li/p/8687059.html