2024年3月9日发(作者:)

1

面向对象编程基础(二)方法中的参数传递

1. 输入下面的类,完成下面的要求

publicclassJLab121{

staticfinalcharsuits[]={'H','S','D','C'};

staticfinalStringranks[]={"A","2","3","4","5","6","7","8","9",

"1","J","Q","K"};

staticCard[]cards=newCard[52];

/**

*初始化扑克牌数组

*/

publicstaticvoidinit(){

for(inti=;i<;i++){

for(intj=;j<;j++){

cards[i*+j]=newCard(suits[i],ranks[j]);

}

}

}

publicstaticvoidswap1(Cardc1,Cardc2){

Cardc=c1;

c1=c2;

c2=c;

}

publicstaticvoidswap1(inti,intj){

Cardc=cards[i];

cards[i]=cards[j];

cards[j]=c;

}

publicstaticvoidswap2(Cardc1,Cardc2){

chars=;

=;

=s;

Stringr=;

=;

=r;

}

/**

*@paramargs

*/

publicstaticvoidmain(finalString[]args){

init();

//任取两张牌

Cardc1=cards[1];

Cardc2=cards[12];

n("第11张牌是:"+c1+"t第13张牌是:"+c2);

}

}

1) 在main方法中,添加下面几行语句,写出并分析结果

swap1(c1,c2);

n("执行swap1(c1,c2)后");

n("c1引用的牌是:"+c1+"tc2引用的牌是:"+c2);

n("第11张牌是:"+cards[10]+"t第13张牌是:

"+cards[12]);

运行结果:第

11

张牌是:

HJ

13

张牌是:

HK

执行

swap1(c1,c2)

c1

引用的牌是:

HJ c2

引用的牌是:

HK

11

张牌是:

HJ

13

张牌是:

HK

2

分析结果:

c1,c2

分别为

cards[10],cards[13]

,故输出:第

11

张牌是:

HJ

13

张牌是:

HK

执行

swap(c1,c2)

c1,c2

只是把值传递给形参,

swap()

中值的变化是形参在变化,与

c1,c2

无关

Cards[10],card[13]

也无发生变化,故输出:第

11

张牌是:

HJ

13

张牌是:

HK

2) 在main方法中,去掉刚才添加的语句,添加下面几行语句,写出并分析结果

swap1(10,12);

n("执行swap1(10,12)后");

n("c1引用的牌是:"+c1+"tc2引用的牌是:"+c2);

n("第11张牌是:"+cards[10]+"t第13张牌是:

"+cards[12]);

运行结果:第

11

张牌是:

HJ

13

张牌是:

HK

执行

swap1(10,12)

c1

引用的牌是:

HJ c2

引用的牌是:

HK

11

张牌是:

HK

13

张牌是:

HJ

分析结果:未交换时,输出第

11

张牌是:

HJ

13

张牌是:

HK

该程序为交换

cards[i]

i=10,13

的牌,

cards[10]

cards[13]

交换即

HJ

HK

交换,但

c1,c2

已初始化,且

swap1(int i,int j)

c1,c2

只负责

i

值传递,与

其本身无关,结果为

cards[10]=” HK” cards[13]=” HJ”

3) 在main方法中,去掉刚才添加的语句,添加下面几行语句,写出并分析结果

swap2(c1,c2);

n("执行swap2(c1,c2)后");

n("c1引用的牌是:"+c1+"tc2引用的牌是:"+c2);

n("第11张牌是:"+cards[10]+"t第13张牌是:

"+cards[12]);

运行结果:第

11

张牌是:

HJ

13

张牌是:

HK

执行

swap2(c1,c2)

c1

引用的牌是:

HK c2

引用的牌是:

HJ

11

张牌是:

HK

13

张牌是:

HJ

分析结果:未交换时,输出第

11

张牌是:

HJ

13

张牌是:

HK

swap2(c1,c2);c1

c2

rank

suit

分别交换,此为

c1,c2

所引用的对象的属性的交换,

c1,c2

引用的牌也变化:

c1

引用的牌是:

HK c2

引用的牌是:

HJ

cards[10]

cards[12]

中的属性也发生交换变化,故第

11

张牌是:

HK

13

张牌是:

HJ

实验十八:异常

3

实验要求和过程

1. public class TestApp{

public static void main(String[] args){

try{

int i = 0;

int j = 1 / i;

String myname=null;

if(()>2)

(“1”);

}catch(NullPointerException e){

(“2”);

}catch(Exception e){

(“3”);

}

}

}

分析上述程序运行后的输出的结果和原因。

输出结果:

3

j

为除式,除数不能为

0

,属于运行异常中的

eticException: / by zero

,不属于

()>2

NullPointerException

的情况,因此输出

3

2. 下面是一个名称为NegativeAmountException的自定义异常类,表示一个不正常的银行账

目事件类。填充下面的语句,完成该类的编写。

public class NegativeAmountException extends Exception{

public NegativeAmountException(String s) {

super(s);

}

}

class Account {

double balance;

// 构造函数,余额为0;

public Account() {

balance = 0;

}

// 构造函数,余额为n,如果初始余额小于0抛出异常

public Account(double n) throws NegativeAmountException {

if (n > 0) {

e = n;

} else {

throw new NegativeAmountException("

余额异常

");

}

}

// 查询余额方法,返回当前余额

public double getBalance() {

return e;

}

// 存款方法,存款数额amount; 如果存款数目小于0抛出异常

public void deposit(double amount) throws NegativeAmountException {

if (amount >= 0) {

balance = amount;

} else {

throw new NegativeAmountException("

存款出错

");

}

}

// 取款方法,取款数额amount; 如果取款数目小于0抛出异常

public void withdraw(double amount) throws NegativeAmountException

{

if (amount < 0) {

4

throw new NegativeAmountException("

操作错误

");

} else if (balance < amount) {

throw new NegativeAmountException("

取款出错

");

} else {

balance -= amount;

}

}

public static void main(String[] args) throws NegativeAmountException

{

Account zqq = new Account();

t(-10);

}

}

运行结果:

Exception in thread "main" NegativeAmountException: 存款出错

at t(:28)

at (:46)

3. 模仿上题中NegativeAmountException自定义异常的写法,根据下面要求写程序。

1) 自定义异常OnlyOneException与NoOprandException,并补充各自类的构造函数,参数

用于保存异常发生时候的信息;

2) 添加main方法,从命令行参数读入两个数据,计算这两个数据的和并输出。

3) 如果参数的数目只要一个,抛出OnlyOneException异常并退出程序的执行;如果没有

参数 ,抛出NoOprandException异常并退出程序的执行;

public class OnlyOneException extends Exception{

public OnlyOneException(String s){

super(s);

}

}

public class NoOprandException extends Exception {

public NoOprandException(String s ){

super(s);

}

}

import r;

public class Test {

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

n("请输入两个数");

Scanner sc=new Scanner();

String ab=();

String[] arr = (",");

if (<2){

if(==0){

throw new NoOprandException("未输入参数");

}

else{

throw new OnlyOneException("仅输入了一个参数");}}

double x=ouble(arr[0]);

double y=ouble(arr[1]);

double sum;

sum=x+y;

n(sum);}

}

4. 为实验15(5),添加一个取款异常WithdrawException,请定义异常类WithdrawException,

要求:

1) 异常对象记录取款发生时的帐户余额、取款额还有取款人。

5

public class WithdrawException extends Exception{

double balance;

double amount;

String name;

public WithdrawException(double balance, double amount, String name)

{

super();

e = balance;

= amount;

= name;

}

@Override

public String toString() {

return "WithdrawException [余额" + balance + ", 取款=" + amount

+ ", 姓名=" + name + "]";

}

}

2) 覆盖继承于超类的方法getMessage(),按以下格式返回信息:

取款人,账号余额,取款额,原因:透支。

@Override

public String getMessage() {

return "WithdrawException 取款人=" + name +",账户余额" + balance +

", 取款额=" + amount

+ "]"+"原因:透支";

}

3) 修改CashAccount的取款方法,当用户取款超出额度时,抛出异常。

Account类中

abstract void withdraw(double amount)throws

BlockException,WithdrawException ;

public class CashAccount extends Account {

public String cashsort;

public String getCashsort() {

return cashsort;

}

public void setCashsort(String cashsort) {

rt = cashsort;

}

public CashAccount(String name, String id, double balance, String

cashsort) {

super(name, id, balance);

rt = cashsort;

}

public void withdraw(double amount) throws

BlockException,WithdrawException{

if((ance() - amount)<0){

throw new WithdrawException(ance(), amount,

);

}

ance(ance() - amount);

}

}

4) 编写一个可执行类Test,创建一个CashAccount的对象,其初始余额为500,连续取

款2次,每次300,写出运行结果。

public class Test {

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

CashAccount debit=new CashAccount("zyq","2",0,"借记卡");

6

t(500);

aw(300);

aw(300);

n(ance());

}}

运行结果:Exception in thread "main" WithdrawException:

WithdrawException 取款人=zyq,账户余额200.0, 取款额=300.0]原因:透支

at aw(:22)

at (:7)

5)继续第一个实验,如果为Account类添加一个String类型的属性 ststus,当它的值

为“blocked”时,取款时发生BlockedException,重写第一个实验(注,取款方法要抛出上述

两个异常),写出异常类BlockedException、新的取款方法,并编写程序验证。

public class BlockException extends Exception{

public BlockException(String s ){

super(s);

}

}

Account类中:

boolean block;

public void setBlock(boolean block) {

= block;

}

CashAccount类中:

public void withdraw(double amount) throws

BlockException,WithdrawException{

if () {

throw new BlockException("账户锁定");

}

if((ance() - amount)<0){

throw new WithdrawException(ance(), amount,

);

}

ance(ance() - amount);

}Test程序:

public class Test {

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

CashAccount debit=new CashAccount("zyq","2",0,"借记卡");

ck(true);

t(500);

aw(300);

aw(300);

n(ance());

}}

运行结果:

Exception in thread "main" BlockException: 账户锁定

at aw(:19)

at (:6)

IO实验

实验要求和过程

1.编写类DemoWriter,在main方法中,利用FileWriter、BufferedWriter流将字符

串”abc”,”123”写到文件c:中,然后再利用FileReader、BufferedReader把字符串从文

件c:读出来并显示。

edReader;

edWriter;

ader;

iter;

7

ption;

publicclassOne{

publicstaticvoidmain(String[]args){

try{

BufferedWriterbw=newBufferedWriter(newFileWriter("c:"));

("abc");

e();

("123");

e();

();

BufferedReaderbr=newBufferedReader(newFileReader("c:"));

Strings=ne();

while(s!=null){

n(s);

s=ne();

}

();

}catch(IOExceptione){

tackTrace();

}

}

}

2.编写类DemoStream,在main方法中,利用FileOutputStream、BufferedOutputStream及

DataOutputStream流将字符串”abc”、字符’h’、整数32、双精度浮点数3.2及布尔值false写

到文件c:中,然后再利用FileInputStream、BufferedInputSteam及DataInputStream把写

入到文件的字符串、字符、整数、双精度浮点数及布尔值从c:中读出来并显示。

edInputStream;

edOutputStream;

edReader;

edWriter;

putStream;

tputStream;

putStream;

tputStream;

ader;

iter;

ption;

publicclassTwo{

publicstaticvoidmain(String[]args){

try{

DataOutputStreambw=newDataOutputStream(newBufferedOutputStream(ne

wFileOutputStream("c:")));

har('h');

TF("abc");

nt(32);

ouble(3.2);

oolean(false);

();

DataInputStreambr=newDataInputStream(newBufferedInputStream(newFi

leInputStream("c:")));

n(ar());

n(F());

n(t());

8

}

}

n(uble());

n(olean());

();

}catch(IOExceptione){

tackTrace();

}

3.编写类Test,在main方法中从键盘上获取若干行数据,每行数据包含一个客户信息,其

内容分项之间用逗号隔开,如“姓名,电话,家庭地址”,将每行信息封装成Record对象然

后保存到集合中,最后将集合中的所有的数据在控制台输出。(提示:用InputStreamReader、

BufferedReader及split方法)

publicclassRecord{

privateStringname;

privateStringphone;

privateStringaddress;

publicRecord(Stringname,Stringphone,Stringaddress){

super();

=name;

=phone;

s=address;

}

publicStringgetName(){

returnname;

}

publicvoidsetName(Stringname){

=name;

}

publicStringgetPhone(){

returnphone;

}

publicvoidsetPhone(Stringphone){

=phone;

}

publicStringgetAddress(){

returnaddress;

}

publicvoidsetAddress(Stringaddress){

s=address;

}

publicStringtoString(){

returnname+","+phone+","+address;

}

}

//

.*;

ist;

;

publicclassThree1{

publicstaticvoidmain(String[]args){

Recordrs[]=newRecord[1];

BufferedReaderbr=newBufferedReader(newInputStreamReader(

));

try{

Strings=ne();

for(inti=;i<1;i++){

Stringss[]=(",");

rs[i]=newRecord(ss[],ss[1],ss[2]);

s=ne();

9

}

();

for(inti=;i<;i++){

n(rs[i].toString());

}

}catch(Exceptione){

//n(sage());

tackTrace();

}

}

}

//

.*;

ist;

;

publicclassThree2{

publicstaticvoidmain(String[]args){

// Listlist=newArrayList();

Recordrs[]=newRecord[1];

BufferedReaderbr=newBufferedReader(

newInputStreamReader());

try{

Strings=ne();

intj=;

//for(inti=;i<1;i++)

while(s!=null){

Stringss[]=(",");

//(newRecord(ss[],ss[1],ss[2]));

rs[j]=newRecord(ss[],ss[1],ss[2]);

s=ne();

j++;

}

();

//for(Recordr:list){

// n(ng());

//}

for(inti=;i

n(rs[i].toString());

}

}

catch(Exceptione){

//n(sage());

tackTrace();

}

}

}

//

.*;

ist;

;

publicclassThree3{

publicstaticvoidmain(String[]args){

Listlist=newArrayList();

BufferedReaderbr=newBufferedReader(newInputStreamReader(

));

try{

Strings=ne();

while(s!=null){

1 0

}

}

Stringss[]=(",");

(newRecord(ss[],ss[1],ss[2]));

s=ne();

}

();

for(Recordr:list){

n(ng());

}

}

catch(Exceptione){

//n(sage());

tackTrace();

}

4.编写程序从文件””上获取若干行数据,每行数据包含一个客户信息,其内

容分项之间用逗号隔开,如“姓名,电话,家庭地址”,将每行信息封装成Record对象

然后保存到集合中,最后将集合中的所有的数据转存入””。

edReader;

edWriter;

ader;

treamReader;

publicclassFour{

publicstaticvoidmain(String[]args){

Recordrs[]=newRecord[1];

try{

BufferedReaderbr=newBufferedReader(newFileReader(""));

Strings=ne();

for(inti=;i<1;i++){

Stringss[]=(",");

rs[i]=newRecord(ss[],ss[1],ss[2]);

s=ne();

}

();

BufferedWriterbw=newBufferedWriter(newFileReader(""));

for(inti=;i<;i++){

(rs[i].toString());

e();

}

();

}catch(Exceptione){

//n(sage());

tackTrace();

}

}

}

5.编写程序,给定一个参数作为查询的给定目录,如果存在的话,列出该目录下的所有子目

录名,如果没有抛出自定义异常“NotFoundDirectoryException”。