1. Write a Java program and output "Hello!" On the screen.
public class Helloworld {
public static void main(String args[]) {
System.out.print ("你好!");
}
}
-
Write a Java program and use if-else statements to determine whether a year is a leap year.
public class LeapYear{ public static void main(String args[]){ int year=2010; if(args.length!=0) year=Integer.parseInt(args[0]); if((year%4==0 &&year%100!=0)||(year%400==0)) System.out.println(year+" 年是闰年。"); else System.out.println(year+" 年不是闰年。"); } }
3. Write a Java program to output 1 on the screen! +2! +3! + ... + 10! And. (P64, Example 2-2)
public class ForTest {
public static void main( String args[] ) {
int i,j,mul,sum=0;
for(i=1;i<=10;i++) {
mul=1;
for(j=1,j<=i;j++) {
mul=mul*j;
}
sum=sum+mul;
}
System.out.println(“1!+2!+3!+……+10!= ”+sum);
}
}
- (1) Write a Circle class, which has:
① A member variable
Radius (private, floating point); // Store the radius of the circle;
②两个构造方法
Circle( ) // 将半径设为0
Circle(double r ) //创建Circle对象时将半径初始化为r
③ 三个成员方法
double getArea( ) //获取圆的面积
double getPerimeter( ) //获取圆的周长
void show( ) //将圆的半径、周长、面积输出到屏幕
(2) Write a cylinder class Cylinder, which inherits from the Circle class above. Also has:
① A member variable
doublehight (private, floating point); // the height of the cylinder;
②构造方法
Cylinder (double r, double h) //创建Circle对象时将半径初始化为r
③ 成员方法
double getVolume( ) //获取圆柱体的体积
void showVolume( ) //将圆柱体的体积输出到屏幕
Write an application, create a class of objects, set the radius of the circle and the height of the cylinder, calculate and display the radius, area, length, and volume of the cylinder.
classCircle {// Define the parent class – garden class
privatedouble radius; //成员变量--园半径
Circle(){ //构造方法
radius=0.0;
}
Circle(doubler) { //构造方法
radius=r;
}
doublegetPerimeter() { //成员方法--求园周长
return2*Math.PI*radius;
}
doublegetArea() { //成员方法--求园面积
returnMath.PI*radius*radius;
}
voiddisp() { //成员方法--显示园半径、周长、面积
System.out.println("园半径="+radius);
System.out.println("园周长="+getPerimeter());
System.out.println("园面积="+getArea());
}
}
class Cylinder extends Circle {// Define sub-category-cylindrical class
privatedouble hight; //成员变量--园柱高
Cylinder(doubler,double h) { //构造方法
super(r);
hight=h;
}
publicdouble getVol() { //成员方法--求园柱体积
returngetArea()*hight;
}
publicvoid dispVol() { //成员方法--显示园柱体积
System.out.println("圆柱体积="+getVol());
}
}
public class TestCylinder {// Define the main class
publicstatic void main (String [] args) {// Main program entry
Circle Ci=new Circle(10.0); // 生成园类实例
Ci.disp(); // 调用园类的方法
CylinderCyl=new Cylinder(5.0,10.0); //生成圆柱类实例
Cyl.disp(); //调用父类方法
Cyl.dispVol(); //调用子类方法
}
}