Java基础编程练习

6-42 Point

There is a class Point that is incompleted. Please complete the class according to the test code in Main.

函数接口定义:
class Point {
private double x;
private double y;
public String toString() {
return "("+this.x+","+this.y+")";
}
}
裁判测试程序样例:
import java.util.Scanner;
class Point {
private double x;
private double y;
public String toString() {
return "("+this.x+","+this.y+")";
}

/** 你所提交的代码将被嵌在这里(替换此行) **/

}

public class Main {
public static void main(String[] args) {
Point a = new Point(); // default ctor, x and y are zeros
Scanner sc = new Scanner(System.in);
double x,y,z;
x = sc.nextDouble();
y = sc.nextDouble();
z = sc.nextDouble();
Point b = new Point(x, y); // ctor by x and y
Point c = new Point(b); // ctor by another Point
a.setY(z);
System.out.println(a);
System.out.println(b);
System.out.println(c);
c.setX(z);
a = b.add(c);
System.out.println(a);
System.out.println("b.x="+b.getX()+" b.y="+b.getY());
sc.close();
}
}
输入样例:
3.14 1.9 2.72
输出样例:
(0.0,2.72)
(3.14,1.9)
(3.14,1.9)
(5.86,3.8)
b.x=3.14 b.y=1.9

以下是答案

package Pta_ex;
import java.util.Scanner;
class Point{
	private double x;
	private double y;
	Point b;
	public String toString() {
		return "("+this.x+","+this.y+")";
	}
	//以下是答案
	Point(){					//无参构造法
		x=0;
		y=0;
	}
	Point(double x,double y){	//带参构造
		this.x=x;
		this.y=y;
	}
	Point(Point b){
		this.x = b.x;
		this.y = b.y; 
	}
	void setX(double z) {
		this.x=z;
	}
	void setY(double z){
		this.y=z;
	}
	double getX() {
		return this.x;
	}
	double getY() {
		return this.y;
	}
	public Point add(Point c) {				//这一开始出现问题,最后传出去的应该是c,而不是this.x,和this.y
											//System.out.println("测试"+c);
		c.x = c.x+this.x;
		c.y = (c.y)*2;
		return c;
	}
	//以上是答案
}
public class Pta_6_42 {
	public static void main(String args[]) {
		Point a = new Point();
		Scanner sc = new Scanner(System.in);
		double x,y,z;
		x = sc.nextDouble();
		y = sc.nextDouble();
		z = sc.nextDouble();
		Point b = new Point(x,y);
		Point c = new Point(b);
		a.setY(z);
		System.out.println(a);
		System.out.println(b);
		System.out.println(c);
		c.setX(z);
		a = b.add(c);
		System.out.println(a);
		System.out.println("b.x="+b.getX()+"b.y="+b.getY());
		sc.close();
	}
}
  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值