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();
}
}