gpt4 book ai didi

java - 如何将对象从一个类传输到另一个类 - JAVA

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

我正在尝试在饼图中显示百分比值,因为我在Personality类中有百分比值,而Chart类是我需要的地方来展示它。我的代码结构如下:

个性.JAVA

   Tree C = gson.fromJson(profile.toString(), Tree.class);  

Tree.SubTree t = C.getTree();
ArrayList<Children> mc = t.getChildren();
Children c1 = mc.get(0);

ArrayList<Children1> c2 = c1.getChildren();
Children1 obj1 = c2.get(0);

private Children1 obj1; //ERROR-ILEGAL START OF EXPRESSION


public Children1 getObj1(){
return this.obj1;
}

/** ArrayList<child2> c3 = obj1.children;
child2 obj2 = c3.get(0);

ArrayList<child3> c4 = obj2.children;
child3 obj3 = c4.get(0); **/


System.out.println(obj1.getPercentage()); //ERROR - IDENTIFIER EXPECTED

Children1.JAVA

   public class Children1 {
private String category;
private String id;
private String name;
private double percentage;
private double sampling_error;
private ArrayList<Children2> children;

public Double getPercentage() {
return percentage;
}
/**
*
* @param percentage
* The percentage
*/
public void setPercentage(Double percentage) {
this.percentage = percentage;
}
}

Tree.JAVA(不确定这个类是否必要,但它就是)

public class Tree {
private SubTree tree;
@Override
public String toString() {
return "ID: " + id + "\n" + "Name: "+ "\n" + tree+ "\n" ;
}
class SubTree{
private String id;
private String name;
private ArrayList<Children> children; //Gets Arraylist from Class - Children


public ArrayList<Children> getChildren() {
return children;
}

public void setChildren(ArrayList<Children> children) {
this.children = children;
}
}

public SubTree getTree() {
return tree;
}

public void setTree() {
this.tree = tree;
}

}

图表类

private PieDataset createDataset(){
Personality m = new Personality();
// Personality.class = Personality();
DefaultPieDataset result = new DefaultPieDataset();
result.setValue("Value1",m.obj1 ); //attempted to get obj1 from Persoanlity Class
result.setValue("Linux", 10);
result.setValue("Mac", 25);
return result;
}

所以整个程序是 - 将普通段落转换为 json,然后在使用 java 值生成图形后解析为 java。因此,在本例中,获取百分比值 obj1 以在 Chart 类 中显示。

希望你们理解这个问题并感谢您抽出时间:)

最佳答案

您必须使 Children1 对象在 Personality 类中可见。目前看来 obj1 只是一个局部变量,其作用域仅对该局部方法可见

如果在 Personality 中,您有一个字段 Children1 obj1,则可以通过本地方法或构造函数来设置它。如果 Children1 obj1 的范围是公共(public)的,或者最好它有一个 getter 方法,那么您可以从 Chart 类 中读取它,假设 Children1 obj1 > 在构造函数中创建,即 Personality m = new Personality();

假设您的 Personality 类类似于

public Personailty {
....
}

然后你将添加,使其看起来像

public Personailty {
....
private Children1 obj1;

public Children1 getObj1(){
return this.obj1;
}
}

关于java - 如何将对象从一个类传输到另一个类 - JAVA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40796190/

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