如何在此代码中使用非静态变量?

时间:2018-12-11 12:27:45

标签: java

所以,我现在正在做我的课程,然后在流程结束时叠加。当我执行变量时,静态程序可以工作,但只能在同一行星的多行中给出结果,而且当设法使代码在没有静态元素的情况下工作时,它给出的是nullpointerexception。

因此,我在这里要求互联网上的某人帮助解释代码中的错误以及如何解决。

这是我的代码:

        import java.util.ArrayList;

public class SolarSystem {

private double luminosity;
private String solarName;
private ArrayList<Planet> planetList = new ArrayList<>();
public SolarSystem(String solarName, double luminosity) {
    this.solarName = solarName;
    this.luminosity = luminosity;
}

public double getLuminosity() {
    return luminosity;
}

public String getsolarName() {
    return solarName;
}

public void addPlanet(String name, double mass, double distance) {
    Planet newPlanet = new Planet();
    planetList.add(newPlanet);
}

public String toString() {
    String myString = solarName + "\n";
    for(int i = 0; i < planetList.size(); i++){      
        String name = Planet.getPlanetname();
          /*So, in this part I need somehow to call components of another class to make this thing work
*but I have no idea how to do it, as if I'll try to make it static to call them directly
*they won't change what I want to do as I have about  7 abjects which I need to output as a text
*similar to test program
*/

        double mass =Planet.getmass(i);
        double distance = ((SolarSystem.Planet) this.Planet).getdist(i);
        double period = ((SolarSystem.Planet) this.Planet).getPeriod();
        String habitable = ((SolarSystem.Planet) this.Planet).getHabitable(i);
            myString = myString + " Planet " + name + " has a mass of " + mass + " Earths, is " + distance + "AU from its star, and orbits in " + period + " years: could be habitable? "+ habitable+ "\n";
    }


    return myString;
}



}





class Planet {
    SolarSystem system;
    private String name;
    private double mass;
    private double distance;
    private double period;
    private String habitable;
    private double luminosity;
    private double sqlum;
    public Planet() {
        this.name=name;
        this.mass = mass;
        this.distance = distance;
        distance=Math.round(distance*1000)/1000;
        this.luminosity=luminosity;
        period = java.lang.Math.sqrt(distance * distance * distance);
       period= Math.round(period*1000.0)/1000.0;
       period=this.period;
        sqlum = java.lang.Math.sqrt(luminosity);
        if ((mass >= 0.6) && (mass <= 7.0) && (distance >= 0.75 * sqlum) && (distance <= 2.0 * sqlum)) {
            habitable = "yes";

        } else {
            habitable = "no";
        }
    }

    public static String getPlanetname() {
        // TODO Auto-generated method stub
        return null;
    }

    public double getPeriod(int i) {
        // TODO Auto-generated method stub
        return period;
    }

    public double getdist(int i) {
        return distance;
    }

    public double getmass(int i) {
        return mass;
    }

    public String getPlanetname(int i) {
        return name;
    }
    public double getPeriod() {
        return period;
    }


    public String getHabitable(int i) {
        return habitable;
    }

    public double setPeriod(int i) {
        this.period=period;
        return period;
    }
    public String setHabitable(int i) {

        return habitable;
    }
    public double setdist(int i) {
        return distance;
    }
    public double mass(int i) {
        return mass;
    }
}

我知道我的主要问题是toString方法,但我只是看不到要更改什么而不能进一步制止它。

这是我要达到的测试程序和结果:

       //Uncomment if using extra tests
       //import org.apache.commons.lang3.StringUtils;

       /*This is the automatic test class for CS-110 coursework 2. The output of the student's program
       * under test should match the string TARGET_OUTPUT_SUN
       */
         public class AutoTest {

static final String TARGET_OUTPUT_SUN = "Our System\n"
        + "Planet Mercury has a mass of 0.055 Earths, is 0.387AU from its star, and orbits in 0.241 years: could be habitable? no\n"
        + "Planet Venus has a mass of 0.815 Earths, is 0.723AU from its star, and orbits in 0.615 years: could be habitable? no\n"
        + "Planet Earth has a mass of 1.0 Earths, is 1.0AU from its star, and orbits in 1.0 years: could be habitable? yes\n"
        + "Planet Mars has a mass of 0.107 Earths, is 1.52AU from its star, and orbits in 1.874 years: could be habitable? no\n"
        + "Planet Jupiter has a mass of 317.8 Earths, is 5.2AU from its star, and orbits in 11.858 years: could be habitable? no\n"
        + "Planet Saturn has a mass of 95.2 Earths, is 9.58AU from its star, and orbits in 29.652 years: could be habitable? no\n"
        + "Planet Uranus has a mass of 14.5 Earths, is 19.2AU from its star, and orbits in 84.13 years: could be habitable? no\n"
        + "Planet Neptune has a mass of 17.1 Earths, is 30.05AU from its star, and orbits in 164.728 years: could be habitable? no\n";

static final String TARGET_OUTPUT_TRAPPIST1 = "Trappist 1\n" +
        "Planet Trappist1b has a mass of 1.017 Earths, is 0.012AU from its star, and orbits in 0.001 years: could be habitable? no\n" +
        "Planet Trappist1c has a mass of 1.156 Earths, is 0.016AU from its star, and orbits in 0.002 years: could be habitable? no\n" +
        "Planet Trappist1d has a mass of 0.297 Earths, is 0.022AU from its star, and orbits in 0.003 years: could be habitable? no\n" +
        "Planet Trappist1e has a mass of 0.772 Earths, is 0.029AU from its star, and orbits in 0.005 years: could be habitable? yes\n" +
        "Planet Trappist1f has a mass of 0.934 Earths, is 0.038AU from its star, and orbits in 0.007 years: could be habitable? yes\n" +
        "Planet Trappist1g has a mass of 1.148 Earths, is 0.049AU from its star, and orbits in 0.011 years: could be habitable? yes\n" +
        "Planet Trappist1h has a mass of 0.331 Earths, is 0.062AU from its star, and orbits in 0.015 years: could be habitable? no\n";

public static void main(String[] args) {


    //Create our solar system
    SolarSystem ourSystem = new SolarSystem("Our System",1.0);

    //Add planets in our solar system
    ourSystem.addPlanet("Mercury", 0.055, 0.387);
    ourSystem.addPlanet("Venus", 0.815, 0.723);
    ourSystem.addPlanet("Earth", 1.0, 1.0);
    ourSystem.addPlanet("Mars", 0.107, 1.52);
    ourSystem.addPlanet("Jupiter", 317.8, 5.20);
    ourSystem.addPlanet("Saturn", 95.2, 9.58);
    ourSystem.addPlanet("Uranus", 14.5, 19.20);
    ourSystem.addPlanet("Neptune", 17.1, 30.05);

    //Check the output for our solar system
    if (ourSystem.toString().equals(TARGET_OUTPUT_SUN)) {
        System.out.println("Solar System: Pass!");
    } else {
        System.out.println("Solar System: Fail!\n*****");
        System.out.println("Expected output:\n");
        System.out.println(TARGET_OUTPUT_SUN);
        System.out.println("\n\nActual output:\n");
        System.out.println(ourSystem.toString());
        // Uncomment if using extra tests*/
        /*System.out.println("\n\nDifferences:");
        System.out.println(StringUtils.difference(ourSystem.toString(),
        TARGET_OUTPUT_SUN));*/
    }

    System.out.println("\n\n");//blank lines to separate output

    //Create the Trappist1 system - a much dimmer star with closer planets
    SolarSystem trappist1 = new SolarSystem("Trappist 1",0.00128);

    //Add planets in Trappist 1 system
    trappist1.addPlanet("Trappist1b", 1.017, 0.012);
    trappist1.addPlanet("Trappist1c", 1.156, 0.016);
    trappist1.addPlanet("Trappist1d", 0.297, 0.022);
    trappist1.addPlanet("Trappist1e", 0.772, 0.029);
    trappist1.addPlanet("Trappist1f", 0.934, 0.038);
    trappist1.addPlanet("Trappist1g", 1.148, 0.049);
    trappist1.addPlanet("Trappist1h", 0.331, 0.062);

    //Check the output for trappist1
    if (trappist1.toString().equals(TARGET_OUTPUT_TRAPPIST1)) {
        System.out.println("Trappist1: Pass!");
    } else {
        System.out.println("Trappist1: Fail!\n*****");
        System.out.println("Expected output:\n");
        System.out.println(TARGET_OUTPUT_TRAPPIST1);
        System.out.println("\n\nActual output:\n");
        System.out.println(trappist1.toString());
        // Uncomment if using extra tests*/
        /*System.out.println("\n\nDifferences:");
        System.out.println(StringUtils.difference(ourSystem.toString(),
        TARGET_OUTPUT_TRAPPIST1));*/
    }
}
}

3 个答案:

答案 0 :(得分:0)

好,所以问题与行星的初始化有关。您永远不会为您的行星设置值。

您必须使用这样的构造函数:

public void addPlanet(String name, double mass, double distance) {
    Planet newPlanet = new Planet(name, mass, distance);
    planetList.add(newPlanet);
}

在您的Planet类中,您的构造函数必须类似于以下内容:

public Planet(String name, double mass, double distance) {
    this.name = name;
    this.mass = mass;
    this.distance = distance;
}

在不将参数传递给构造函数的情况下,这些值永远不会设置,并且始终为null。

答案 1 :(得分:0)

首先是这个:

public void addPlanet(String name, double mass, double distance) {
    Planet newPlanet = new Planet();
    planetList.add(newPlanet);
}

此方法无法像这样工作。当前发生的情况如下:使用行星数据调用方法Solarsystem.addPlanet(..),接下来创建一个新的行星(它是空的!)并将其添加到列表中。 您将一个包含所有空字段的行星添加到列表中,无论您提交了哪些参数作为参数。

要执行此操作,请先构建行星或分配变量。我们稍后再谈。 接下来是您的星球构造器。 尽管这种想法还行(在实例化的同时构建一个新的星球),但是代码却无法正常工作。同样,所有字段(质量,名称等)均为空。要使这两种方法有效,您需要分配变量。

public Planet() {
        this.name=name;
        this.mass = mass;
        this.distance = distance;
        distance=Math.round(distance*1000)/1000;
        this.luminosity=luminosity;
        period = java.lang.Math.sqrt(distance * distance * distance);
       period= Math.round(period*1000.0)/1000.0;
       period=this.period;
        sqlum = java.lang.Math.sqrt(luminosity);
        if ((mass >= 0.6) && (mass <= 7.0) && (distance >= 0.75 * sqlum) && (distance <= 2.0 * sqlum)) {
            habitable = "yes";

        } else {
            habitable = "no";
        }
    }

尝试以下操作:

public void addPlanet(String name, double mass, double distance) {
    Planet newPlanet = new Planet(name, mass, distance);
    planetList.add(newPlanet);
}

(注意到数据已经传递到地球上了吗?)

public Planet(String name, double mass, double distance) {
        this.name=name;
        this.mass = mass;
        this.distance=Math.round(distance*1000)/1000;
        this.luminosity=luminosity;//<this is still empty now and could cause a nullpointer
        this.period = java.lang.Math.sqrt(distance * distance * distance);
       this.period= Math.round(period*1000.0)/1000.0;//this overrides the above value
        sqlum = java.lang.Math.sqrt(luminosity);
        if ((mass >= 0.6) && (mass <= 7.0) && (distance >= 0.75 * sqlum) && (distance <= 2.0 * sqlum)) {
            habitable = "yes";

        } else {
            habitable = "no";
        }
    }

但是最好的方法是执行以下操作;

class Planet {
    private String name;
    private double mass;
    private double distance;
    private double period;
    private bool habitable;
    private double luminosity;
    private double sqlum;

    public Planet() {
    }
    public void setName(String name){
        this.name=name;}
    public String getName(){
        return this.name;}
    public void setMass(double mass){
        this.mass=mass;}
    public double getMass(){
        return this.mass;}
    public void setDistance(double distance){
        this.distance=Math.round(distance*1000)/1000;}
    public double getDistance(){
        return this.distance;}
    public void setPeriod(double period){
        this.period=period;}
    public double getPeriod(){
        return this.period;}
    public double calculatePeriod(){
        if(this.distance!=0.0){
            double tmpPeriod = java.lang.Math.sqrt(this.distance * this.distance * this.distance);
            this.period= Math.round(tmpPeriod*1000.0)/1000.0;
        }
        return this.period;}
    public void setLuminosity(double luminosity){
        this.sqlum = java.lang.Math.sqrt(luminosity);}
    public double getLuminosity(){
        return this.sqlum;}
    public bool isPlanetHabitable(){
         if ((this.mass >= 0.6) && (this.mass <= 7.0) && (this.distance >= 0.75 * this.sqlum) && (this.distance <= 2.0 * this.sqlum)) {
            this.habitable = true;

        } else {
            this.habitable = false;
        }
    return habitable;}


}

然后,您可以在addPlanet方法中进行下一个操作:

public void addPlanet(String name, double mass, double distance, double luminosity) {
    Planet newPlanet = new Planet();
newPlanet.setName(name);
newPlanet.setMass(mass);
newPlanet.setDistance(distance);
newPlanet.calculatePeriod();
newPlanet.setLuminosity(luminosity);
    planetList.add(newPlanet);
}

现在,将填写所有字段的星球添加到您的列表中。

答案 2 :(得分:0)

经过几次更改,我通过了您的测试。

public class SolarSystem {

private final double luminosity;
private final String solarName;
private final ArrayList<Planet> planetList = new ArrayList<>();

public SolarSystem(String solarName, double luminosity) {
    this.solarName = solarName;
    this.luminosity = luminosity;
}

public double getLuminosity() {
    return luminosity;
}

public String getSolarName() {
    return solarName;
}

public void addPlanet(String name, double mass, double distance) {
    Planet newPlanet = new Planet(name, mass, distance, luminosity);
    planetList.add(newPlanet);
}

@Override
public String toString() {
    String myString = solarName + "\n";
    for (int i = 0; i < planetList.size(); i++) {
        Planet planet = planetList.get(i);

        String name = planet.getName();
        double mass = planet.getMass();
        double distance = planet.getDistance();
        double period = planet.getPeriod();
        String habitable = planet.getHabitable();
        myString = myString + "Planet " + name + " has a mass of " + mass + " Earths, is " + distance
                + "AU from its star, and orbits in " + period + " years: could be habitable? " + habitable + "\n";
    }

    return myString;
}
}

class Planet {
SolarSystem system;
private final String name;
private final double mass;
private final double distance;
private double period;
private String habitable;
private final double luminosity;
private final double sqlum;

public Planet(String name, double mass, double distance, double luminosity) {
    this.name = name;
    this.mass = mass;
    this.distance = Math.round(distance * 1000.0) / 1000.0;
    this.luminosity = luminosity;
    this.period = Math.round(Math.sqrt(distance * distance * distance) * 1000.0) / 1000.0;
    this.sqlum = java.lang.Math.sqrt(luminosity);
    if ((mass >= 0.6) && (mass <= 7.0) && (distance >= (0.75 * sqlum)) && (distance <= (2.0 * sqlum))) {
        habitable = "yes";

    } else {
        habitable = "no";
    }
}

public SolarSystem getSystem() {
    return system;
}

public void setSystem(SolarSystem system) {
    this.system = system;
}

public double getPeriod() {
    return period;
}

public void setPeriod(double period) {
    this.period = period;
}

public String getHabitable() {
    return habitable;
}

public void setHabitable(String habitable) {
    this.habitable = habitable;
}

public String getName() {
    return name;
}

public double getMass() {
    return mass;
}

public double getDistance() {
    return distance;
}

public double getLuminosity() {
    return luminosity;
}

public double getSqlum() {
    return sqlum;
}

}