所以我试图在类中编写一个使用Point和Line的代码。它的目的是创建一个有两个点的线,然后找到该线的斜率。这就是代码的样子
public class LineMain{
public static void main (String[]args){
Point p1=new Point(22,3);
Point p2=new Point(4,7);
Line Line1=new Line(p1,p2);
System.out.println(Line1.getSlope());
}
}
public class Line{
private Point p1;
private Point p2;
public Line(Point p1, Point p2){
this.p1=p1;
this.p2=p2;
}
public Point getP1(){
return p1;
}
public Point getP2(){
return p2;
}
public double getSlope(){
int slope;
slope = ((p2.y-p1.y)/(p2.x-p1.x));
return slope;
}
}
public class Point{
private int x;
private int y;
/*
public Point(){
this(0,0);
}
*/
public Point(){
x=0;
y=0;
}
public Point(int x, int y){
this.x=x;
this.y=y;
}
public Point(Point p){
x=p.x;
y=p.y;
}
/*
public Point (int x1,int y1){
x=x1;
y=y1;
}
*/
public int getX(){
return x;
}
public int getY(){
return y;
}
public void setX(int x){
this.x=x;
}
public void setY(int y){
this.y=y;
}
public String toString(){
return "("+x+", "+y+")";
}
public double distance(Point other){
double x1=other.x;
double y1=other.y;
double z=Math.pow((x1-x),2)+Math.pow((y1-y),2);
return z;
}
public double slope(Point other){
double x1=other.x;
double y1=other.y;
if (x1==x){
throw new IllegalArgumentException("no");
}else{
double z=(y1-y)/(x1-x);
return z;
}
}
}
但每次我尝试运行代码时都会弹出错误:
Line.java:24: error: y has private access in Point
slope = ((p2.y-p1.y)/(p2.x-p1.x));
^
Line.java:24: error: y has private access in Point
slope = ((p2.y-p1.y)/(p2.x-p1.x));
^
Line.java:24: error: x has private access in Point
slope = ((p2.y-p1.y)/(p2.x-p1.x));
^
Line.java:24: error: x has private access in Point
slope = ((p2.y-p1.y)/(p2.x-p1.x));
^
4 errors
请帮忙!
答案 0 :(得分:4)
你有两个选择,虽然我真的希望你选择后者。
将Point
字段设为公开。这将允许您使用它们,因为您目前以违反惯例为代价。
public class Point {
public double x, y; // Possible
// constructor detail
}
为getX()
的字段创建getY()
和Point
,并将其保留为private
。但是,您必须重写x
和y
的使用,但代价是保留惯例。
public class Point {
private double x, y;
// constructor detail
public double getX() {
return x;
}
public double getY() {
return y;
}
}
答案 1 :(得分:0)
您需要将方法getX()
和getY()
添加到Point
课程,然后在Line
课程中使用它们。