Java语法基础练习题2

来源:互联网 发布:村上春树跑步语录知乎 编辑:程序博客网 时间:2024/05/19 16:20

Part 1 类的定义

课堂练习1

请定义一个交通工具(Vehicle)的类,其中有:

Ø 属性:速度(speed),体积(size)等

Ø 方法:移动(move()),设置速度(setSpeed(int speed)),设置体积(setSize(int size))加速speedUp(),减速speedDown()等

在测试类Vehicle中的main()中实例化一个交通工具对象,通过方法给它初始化speed,size的值,并打印出来。另外,调用加速,减速的方法对速度进行改变。

import java.util.Scanner;
public class TestVehicle {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.print("请输入交通工具的名字:");
String name=input.next();
Vehicle vehicle=new Vehicle();
System.out.println(name+"通过方法设置速度为:"+vehicle.setSpeed(10)+",体积为"+vehicle.setSize(50));
System.out.println(name+"加速后,当前速度为:"+vehicle.speedUp());
System.out.println(name+"减速后,当前速度为:"+vehicle.speedDown());
}
}

public class Vehicle {
int speed,size;
public void Vehicle() {
speed=0;
size=0;
}
int setSpeed(int speed){
this.speed=speed;
return speed;
}
int setSize(int size){
this.size=size;
return size;
}
void move(){

}
int speedUp(){
speed++;
return speed;
}
int speedDown(){
speed--;
return speed;
}
}


课堂练习2

打印当前时间。学习使用Date类和Calendar类。(教材P194页)

import java.util.Calendar;
public class Date {
public static void main(String[] args) {
java.util.Date nowTime=new java.util.Date();
System.out.println("现在时间是:"+nowTime);
String pattern="%tY-%<tm-%<td(%<tA) %<tT";
String string=String.format(pattern, nowTime);
System.out.println(string);
Calendar calendar=Calendar.getInstance();
calendar.set(2017,9,22,17,50,58);
string=String.format("%tY年%<tb%<td日(%<tT),所在时区%<tZ与GMT相差%<tz小时",calendar);
System.out.println(string);
}
}


Part 2 构造函数

课堂练习3

Point基础,定义一个平面中的Circle类

1、 编写一个无参的构造函数

2、 编写一个有参的构造函数

3、 在主函数中调用无参的构造函数生成圆的实例c1,调用有参的构造函数生成圆的实例c2,调用实例方法判断c1c2是否相重叠。

import java.util.Scanner;
public class TestCircle {
public static void main(String[] args) {
Circle c1=new Circle();
c1.printPoint();
Scanner reader=new Scanner(System.in);
System.out.println("请输入新圆心坐标(x,y),半径r:");
double x,y,r;
x=reader.nextDouble();
y=reader.nextDouble();
r=reader.nextDouble();
Circle c2=new Circle(x,y,r);
c2.printPoint();
c1.Point(c2);
}
}

public class Circle {
double x;
double y;
double r;
Circle(){
x=1.0;
y=1.0;
r=1.0;
}
Circle(Double xx,Double yy,double rr){
x=xx;
y=yy;
r=rr;
}
void printPoint(){
System.out.println("圆心的坐标为:("+x+","+y+"),"+"半径为:"+r);
}
void Point(Circle c) {
if(x==c.x&&y==c.y&&r==c.r)
System.out.println("c1和c2相重叠");
else
System.out.println("c1和c2不重叠");
}
}