System.out.print(b[i]+","+a[i]+",");
}
}
}
〔3〕上下文PrintGame.java
publicclassPrintGame{
PrintCharacterstrategy;
publicvoidsetStrategy(PrintCharacterstrategy){
this.strategy=strategy;
}
publicvoidgetPersonScore(char[]a,char[]b){
if(strategy==null)
System.out.println("sorry!
");
else
strategy.printTable(a,b);
}
}
应用以上策略:
publicclassApplication{
publicstaticvoidmain(Stringargs[]){
char[]a=newchar[26];
char[]b=newchar[26];
for(inti=0;i<=25;i++){
a[i]=(char)('a'+i);
}
for(inti=0;i<=25;i++){
b[i]=(char)('A'+i);
}
PrintGamegame=newPrintGame();//上下文对象
game.setStrategy(newPrintStrategyOne());//上下文对象使用策略一
System.out.println("方案1:
");
game.getPersonScore(a,b);
game.setStrategy(newPrintStrategyTwo());//上下文对象使用策略二
System.out.println("方案2:
");
game.getPersonScore(a,b);
}
}
习题9
1.A,B,D
2.Love:
Game
3.13
abc夏日
4.13579
5.9javaHello
6.
publicclassXiti6{
publicstaticvoidmain(Stringargs[]){
Strings1,s2,s3,t1="ABCDabcd";
System.out.println("字符串原来是这个样子:
"+t1);
s1=t1.toUpperCase();
System.out.println("字符串中的小写字母变成大写是这个样子:
"+s1);
s2=t1.toLowerCase();
System.out.println("字符串中的大写字母变成小写是这个样子:
"+s2);
s3=s1.concat(s2);
System.out.println("大写字符串连接小写字符串是这个样子:
"+s3);
}
}
7.
classXiti7
{publicstaticvoidmain(Stringargs[])
{Strings="中华人民共和国";
chara=s.charAt(0);
charb=s.charAt(6);
System.out.println("第一个字符:
"+a);
System.out.println("最后一个字符:
"+b);
}
}
8.
importjava.util.*;
classXiti8
{publicstaticvoidmain(Stringargs[]){
intyear,month;
System.out.println("请输入年份和月份,每输入一个数回车确认");
Scannerreader=newScanner(System.in);
year=reader.nextInt();
month=reader.nextInt();
String[]day=newString[42];
System.out.println("日一二三四五六");
Calendarrili=Calendar.getInstance();
rili.set(year,month-1,1);//将日历翻到year年month月1日,注意0表示一月...11表示十二月
int星期几=rili.get(Calendar.DAY_OF_WEEK)-1;
intdayAmount=0;
if(month==1||month==3||month==5||month==7||month==8||month==10||month==12)
dayAmount=31;
if(month==4||month==6||month==9||month==11)
dayAmount=30;
if(month==2)
if(((year%4==0)&&(year%100!
=0))||(year%400==0))
dayAmount=29;
else
dayAmount=28;
for(inti=0;i<星期几;i++)
day[i]="";
for(inti=星期几,n=1;i<星期几+dayAmount;i++){
if(n<=9)
day[i]=String.valueOf(n)+"";
else
day[i]=String.valueOf(n);
n++;
}
for(inti=星期几+dayAmount;i<42;i++)
day[i]="";
for(inti=0;i<星期几;i++)
{day[i]="**";
}
for(inti=0;i{if(i%7==0)
{System.out.println("");
}
System.out.print(""+day[i]);
}
}
}
9.
importjava.util.*;
classXiti9
{publicstaticvoidmain(Stringargs[]){
intyear1,month1,day1,year2,month2,day2;
Scannerreader=newScanner(System.in);
System.out.println("请输入第一个日期的年份月份日期,每输入一个数回车确认");
year1=reader.nextInt();
month1=reader.nextInt();
day1=reader.nextInt();
System.out.println("请输入第二个日期的年份月份日期,每输入一个数回车确认");
year2=reader.nextInt();
month2=reader.nextInt();
day2=reader.nextInt(