How to use methods and such

My task is to write a class called Point, which has two data members of type double. Default constructor should initialize point to origin. Also create an overloaded constructor fot the Point class which takes two doubles as parameters. This class should have methods getX, getY, setX, setY, and setXY in order to get and set data members. Also include toString method for this class that outputs coordinates for this point.

This is what my code looks like:

import java.util.Scanner;

public class Point {

private double x;
private double y;

public void getX(){
      Scanner scan = new Scanner(System.in);
      double x = scan.nextInt();
}
public double setX(double x){
    return x;
}
public void getY(){
      Scanner scan = new Scanner(System.in);
      double y = scan.nextInt();
}
public double sety(double y){
    return y;
}
public void setXY(double x, double y){
    double xy = (x + y);
}
public String toString(double xy){
    return xy;
}

}

Can someone assist me in telling me what I am doing wrong?


Your Point will be used in other code eg a runnable class with a main method.

From this other code your will instantiate a Point Object ie by using the Contructor

eg

Point myPoint = new Point (1.23, 3.45);

See how the constructor is being passed the data. Your Point class then should have a constructor like

public Point (double x, double y) {
    this.x = x;
    this.y = y;
}

If you use an IDE like Eclipse and declare fields such as

 double x;
 double y;

then it is simply a case on right clicking on the field to automatically generate setters and getters and they will look like

public void setX (double x) {
  this.x = x;
}

The idea of this type of class is to hold data. As the data ie x and y is being already held, then it is not necessary to pass this data into the class again to simply print it out, thus

public String toString(){
  return "x:" + x + " y:" + y);
}

Based on the above, I am sure you can figure out the setXY method.

链接地址: http://www.djcxy.com/p/83256.html

上一篇: setSize()方法

下一篇: 如何使用方法等