System.out.println(myarrays[i]);
}
}
catch(ArrayIndexOutOfBoundsExceptione){
System.out.println(e.toString());
}
}
}
12.编程求出2~n之间的所有素数。
n由键盘输入。
解答:
importjava.io.*;
classExam3_1{
publicstaticvoidmain(String[]args)throwsIOException{
Stringstr;
intn,i,j;
BufferedReaderin=newBufferedReader(newInputStreamReader(System.in));
str=in.readLine();
in.close();
n=Integer.valueOf(str).intValue();
System.out.println("2");
for(i=3;i<=n;i=i+2){
intk=(int)Math.sqrt(i)+1;
for(j=2;j<=k;j++)
if(i%j==0)break;
if(j>=k)System.out.println(i);
}
}}
13.按以下要求编程
(1)编写Animal类,定义leg属性、有参构造函数对leg赋初值,定义空的sound()方法;
(2)编写Flyable接口,定义speed()方法;
(3)编写Glede类继承Animal类并实现Flyable接口,定义speed属性,有参构造方法对leg和speed赋初值,speed()方法返回speed属性,sound()方法输出“嘎……”。
(4)编写测试程序,定义包含2个元素的Glede对象数组,分别调用speed()方法和sound()方法。
解答:
classAnimal{
intleg;
publicAnimal(){}
publicAnimal(intleg){this.leg=leg;}
}
interfaceFlyable{
intspeed();
}
classGledeextendsAnimalimplementsFlyable{
intspeed;
publicGlede(intspeed){
super
(2);
this.speed=speed;
}
publicintspeed(){
returnspeed;
}
publicvoidsound(){
System.out.println("嘎……");}
}
classexam3_3{
publicstaticvoidmain(Stringargs[]){
Glede[]glede=newGlede[2];
glede[0]=newGlede(200);
glede[1]=newGlede(150);
System.out.println(glede[0].speed());
glede[0].sound();
System.out.println(glede[1].speed());
glede[1].sound();
}}
14.编写程序,将从命令行获得字符串转换为整型值,处理当args[0]=“56k9”时的情况(要求捕获异常NumberFormatException并处理)
解答:
classExam3_4{
publicstaticvoidmain(Stringargs[]){
try{
Stringstr=args[0];
intn=Integer.parseInt(str);
}catch(NumberFormatExceptionne)
{System.out.println(ne);}}}
15.连续写下从整数1开始到某个正整数N之间的所有整数时,能得到如下的数字序列:
1234567891011121314151617181920212223……,请编写程序输入正整数N,并计算得到的数字序列中数字字符的个数,程序的运行效果如下图所示。
解答:
importjava.util.Scanner;
publicclassEx{
publicstaticvoidmain(String[]args)throwsException
{
inti=1,sum=0;
Scannersr=newScanner(System.in);
System.out.print("请输入正整数N:
");
intn=sr.nextInt();
for(i=1;i<=n;i++){
sum+=(i+"").length();
}
System.out.print("序列中的数字字符个数为:
");
System.out.println(sum);
}
}
16.按以下要求定义类Point表示平面上的一个点,定义类Circle表示平面上的一个圆,具体要求如下:
(1)Circle类的实例属性:
圆心x坐标(xpoint)、圆心y坐标(ypoint)和半径(radius)。
(2)Point类的实例属性:
点的x坐标(x)、点的y坐标(y)。
(3)分别编写Point类和Circle类的构造方法,对属性进行初始化。
(4)在Point类中编写方法计算两个点之间的距离。
方法格式:
publicstaticdoubledistance(Pointp1,Pointp2)
(5)在Circle类中编写方法判断一个点是否在圆内。
方法格式:
publicstaticbooleanisInside(Circlec,Pointp)
(6)在测试类中实例化类的对象并调用方法完成信息的输出。
解答:
publicclassCircle{
privatedoublexpoint;
privatedoubleypoint;
privatedoubleradius;
publicCircle(doublexpoint,doubleypoint,doubleradius){
this.xpoint=xpoint;
this.ypoint=ypoint;
this.radius=radius;
}
publicstaticbooleanisInside(Circlec,Pointp){
doubles=(c.xpoint-p.x)*(c.xpoint-p.x)+(c.ypoint-p.y)*(c.ypoint-p.y);
if(s<(c.radius*c.radius))
returntrue;
else
returnfalse;
}
}
publicclassPoint{
publicdoublex;
publicdoubley;
publicPoint(doublex,doubley){
this.x=x;
this.y=y;
}
publicst