1.请定义一个交通工具(Vehicle)的类其中有: 属性: 速度(speed)、 体积(size)等,方法:移动(move())、设置速度(setSpeed(int speed))、加速 speedUp()、减速 speedDown()等。最后在测试类 Vehicle 中的 main()中实例化一个交通工具对象并通过方法给它初始化 speed,size 的值并且通过打印出来。另外调用加速、减速的方法对速度进行改变。
public class Vehicle {
int speed;
int size;
//提供一个可以生成速度的构造方法用来生成对象
public Vehicle(int speed, int size){
this.speed = speed;
this.size = size;
System.out.println(speed+" , "+size);
}
public void move(Vehicle m){
Scanner sc = new Scanner(System.in);
System.out.println("请输入初始速度:");
m.speed = sc.nextInt();
System.out.println("请输入体积:");
m.size =sc.nextInt();
}
public void speedUp(Vehicle m){
int i = m.speed+10;
System.out.println("加速后速度为:"+i);
}
public void speedDown(Vehicle m){
int j = m.speed-5;
System.out.println("减速后速度为:"+j);
}
public static void main(String[] args) {
Vehicle m = new Vehicle(0,0);
m.move(m);
m.speedUp(m);
m.speedDown(m);
}
}
2.编写 Java 程序用于显示人的姓名和年龄。定义一个人类Person。 该类中应该有两个私有属性: 姓名 (name) 和年龄 (age) 。定义构造方法用来初始化数据成员。再定义显示(display()) 方法将姓名和年龄打印出来。在 main 方法中创建人类的实例然后将信息显示。
public class Person2 {
String name;
int age;
public Person2(String name,int age){
this.name = name;
this.age = age;
}
public Person2() {
// TODO 自动生成的构造函数存根
}
public void display(String name,int age){
Person why = new Person("name",age);
Scanner sc = new Scanner(System.in);
System.out.println("请输入名字");
why.name = sc.nextLine();
System.out.println("请输入年龄");
why.age = sc.nextInt();
System.out.println(why.name+" "+why.age);
}
public static void main(String[] args) {
Person2 r= new Person2("null",0);
r.display(null,0 );
}
}
3.输入两个坐标 计算两个点的距离
public class Point {
int x ;
int y ;
public Point(int x,int y){
this.x = x;
this.y = y;
}
public void setPoint(Point p){
Scanner sc = new Scanner(System.in);
System.out.println("请输x坐标:");
p.x = sc.nextInt();
System.out.println("请输y坐标:");
p.y = sc.nextInt();
}
public void count(Point p1,Point p2){
double d = Math.pow(Math.pow(p2.x-p1.x, 2)+Math.pow(p2.y-p1.y, 2),0.5);
System.out.println(d);
}
public static void main(String[] args) {
Point p1 = new Point(1,1);
Point p2 = new Point(10,10);
p1.setPoint(p1);
p2.setPoint(p2);
p1.count(p1, p2);
}
}