dangling else problem
package javaclass0416;
//data field는 두개 method는 1개, 여기서 method는 constructor
public class Point {
double x,y;
static int s;
Point(double initx, double inity)
{
x=initx;
y=inity;
s=5;
}
double distance(Point other) {
double dx=x-other.x;
double dy=y-other.y;
return Math.sqrt(dx*dx+dy*dy);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Point p=new Point(1,2);
Point q=new Point(4,6);
//에러가 난다! Point.x=666.66;
Point.s=7;
System.out.println("px = "+p.x+", py = "+p.y+", ps = "+p.s);
System.out.println("qx = "+q.x+", qy = "+q.y+", qs = "+q.s);
System.out.println("distance = "+p.distance(q));
}
}
package javaclass0416;
public class Circle {
Point center;
double r;
Circle(double initx, double inity, double initr){
center=new Point(initx, inity);
r=initr;
}
boolean isHit(Point p) {
/*
double dx=center.x-p.x;
double dy=center.y-p.y;
double dist=Math.sqrt(dx*dx+dy*dy);
*/
double dist=center.distance(p);
return dist<r;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Circle c=new Circle(1,2,3);
Point p=new Point(1,1);
if(c.isHit(p)) {
System.out.println("hit");
}
else {
System.out.println("miss");
}
}
}
extension이용
package javaclass0416;
public class Circle extends Point{
double r;
Circle(double initx, double inity, double initr){
super(initx, inity);
x=initx;
y=inity;
r=initr;
}
boolean isHit(Point p) {
/*
double dx=center.x-p.x;
double dy=center.y-p.y;
double dist=Math.sqrt(dx*dx+dy*dy);
*/
double dist=distance(p);
return dist<r;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Circle c=new Circle(1,2,3);
Point p=new Point(1,1);
if(c.isHit(p)) {
System.out.println("hit");
}
else {
System.out.println("miss");
}
}
}