gpt4 book ai didi

java - Java中如何将参数从一个类传递到另一个类?

转载 作者:行者123 更新时间:2023-12-01 17:29:13 25 4
gpt4 key购买 nike

我想将 Point 的坐标传递给 Shape addPoint()。并将这些坐标存储到链表中头等舱 - 点求两点之间的距离


package com.company;
import java.lang.Math;
import java.util.Scanner;

public class Point {
//fields
public int x; //coordinate of point
public int y;

//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}

//method
//getters
public int getX() {
return x;
}
public int getY() {
return y;
}
//setters
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}

//function distance
public void distance(Point point) {
double res = Math.sqrt(
Math.pow(getX() - point.getX(), 2) +
Math.pow(getY() - point.getY(), 2)
);
System.out.println(res);
}
}

第二类 - 形状在这里我尝试使用函数来将这一点的坐标添加到链接列表中但我不知道,这对不对?我需要以某种方式在此类中传递这些坐标,但不知道如何编码。

package com.company;
import java.util.*;

public class Shape {

public void addPoint(Point receivedPoint) {
// Creating object of class linked list
LinkedList<Point> points = new LinkedList<Point>();
// Adding elements to the linked list
points.add(receivedPoint);
points.add(receivedPoint);
System.out.println("Linked list : " + points);
}
}

最佳答案

创建一个驱动程序类并调用addPoint,如下所示,

public class Driver {
public static void main(String[] args) {
Point point = new Point(10,20); //create point object
Shape shape = new Shape();
shape.addPoint(point); //call method
}
}

关于java - Java中如何将参数从一个类传递到另一个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61155924/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com