Не могу заставить программу изменить объект внутри массива - PullRequest
0 голосов
/ 11 декабря 2018

Итак, я очистил метод toString, но застрял еще раз.Я не могу найти способ, как изменить код, чтобы он работал так, чтобы показать не только последнюю из планет.Я не вижу проблемы.По идее он должен записать все планеты, но на самом деле он записывает только последнюю планету несколько раз.

Это мой код:

         import java.util.ArrayList;

public class SolarSystem {
private static int i = 0;
private static double luminosity;
private String solarName;
private ArrayList<Planet> planetList = new ArrayList<>(i);
public static final int PLANET_MAX = 10;
public static int planetCount = 0;
SolarSystem(String solarName, double luminosity) {
    this.solarName = solarName;
    this.luminosity = luminosity;
}

public double getLuminosity() {
    return luminosity;
}

public void setLuminosity(double luminosity) {
    this.luminosity = luminosity;
}

public String getsolarName() {
    return solarName;
}

public String getsolarname() {
    return solarName;
}

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

public String toString() {
    String myString = solarName + "\n";
    for(int i = 0; i < planetList.size(); i++){
        String name = Planet.getPlanetname(i);
        double mass = Planet.getma(i);
        double distance = Planet.getdist(i);
        double period = Planet.getPeriod(i);
        String habitable = 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;
}



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

        } else {
            habitable = "no";
        }
    }

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

    public static double getdist(int i) {
        return dist;
    }

    public static double getma(int i) {
        return ma;
    }

    public static String getPlanetname(int i) {
        return Planetname;
    }

    public void setPlanetname(String planetname) {
        Planet.Planetname = planetname;
    }

    public double getPeriod() {
        return period;
    }

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

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

    public String setHabitable(String habitable) {
        return Planet.habitable = habitable;
    }
}
}

И это моя программа тестирования:

         //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 голосов
/ 11 декабря 2018

Объявление атрибутов класса Planet как static означает, что все экземпляры Планеты будут иметь одинаковые атрибуты.

Вы должны изменить объявление атрибутов на:

private  String Planetname;
private  double ma;
private  double dist;
private  double period;
private  String habitable;
private double luminos;
private double sqlum;

Затем вы должны также изменить сигнатуры методов, чтобы удалить ключевое слово static.Поскольку ваши атрибуты больше не являются статичными, метод доступа к ним не может быть статическим.

Пример:

public static String getPlanetname(int i) {

Должен быть изменен на:

public String getPlanetname(int i) {

И, наконец,у вас есть проблема в цикле for

for(int i = 0; i < planetList.size(); i++){
    Planet p = planetList.get(i); // <-- Here you get the Planet at the desired index
    String name = p.getPlanetname(i);  // The parameter i here is useless
    //...
}
0 голосов
/ 11 декабря 2018

Вы используете static, когда не должны.

private static String Planetname;

static означает, что поле является свойством класса, а не экземпляра.Поскольку существует только один class объект (представьте себе «только одно место в памяти, в котором хранятся свойства класса»), по сути, только в одном месте в памяти для вашей программы для хранения названия планеты .Поэтому, когда вы создаете новый Planet, вы перезаписываете этот бит памяти новым именем.

0 голосов
/ 11 декабря 2018

Объявление полей как статических означает, что каждая планета имеет одинаковые значения, поэтому у каждой планеты будет последнее значение, которое вы установили.Не используйте статические поля, если вы хотите, чтобы каждая планета имела разные значения.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...