Question

I am trying to make a Point class. I am not sure what to put in the main method and I think I have some errors in the code as well.

import java.awt.*; 
public class Point { 
int x; // Each Point object has 
int y; // an int x and y inside. 

 public static void main(String[]args)
 {

 }

 public static void draw(Graphics g) { // draws this point 
 g.fillOval(p1.x, p1.y, 3, 3); 
 g.drawString("(" + p1.x + ", " + p1.y + ")", p1.x, p1.y); 
 } 

 public void translate(int dx, int dy) { // Shifts this point's x/y 
 int x = x + dx; // by the given amounts. 
 int y = y + dy; 
 } 

 public double distanceFromOrigin() { // Returns this point's 
 Point p = new Point(); // distance from (0, 0). 
 double dist = Math.sqrt(p.x * p.x + p.y * p.y); 
 return dist; 
 }     
} 
Was it helpful?

Solution

  • I see at least one error: distanceFromOrigin -- you should not create a new Point object, for if you do, the distance will always be 0. Use the x and y you have.
  • Also, your class has no constructor, and you need at least two, one a default constructor that sets x and y to 0, a constructor that takes 2 ints to allow setting of x and y.
  • Also, your x and y variables should be private, and the class should provide getter methods for both, and possibly setter methods, if these are desired.

As for your main method, put whatever you want or are required to put in there. I suspect that you'll want to create a few of your Point objects and test their methods.

As an aside, if this were my code, I'd rename the class to something else so as to not have a name clash with java.awt.Point.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top