在字符串中添加每个int的总数

时间:2014-02-28 00:06:47

标签: java string

我在一个字符串中有9个数字。我想把它们加在一起。我不确定我错过了什么我一直在卫星上收到错误。

写这个的正确方法是什么? 卫星在Planet类中定义,这是太阳系类:卫星保存每个行星卫星的数量。

好的,我发布了完整的代码。在司机我添加行星和他们有多少个卫星。我想在SolarSystem类和System.out.println中将所有卫星一起添加到它们

package planets;

public class Planet  {


    String name;
    int moons;

    public Planet(String name, int moons)
    {
        this.moons = moons;
        this.name = name;               
    }

    public String toString() {
        return "The Planet " + name  + " Has " + moons + " Moon(s) \r\n ";
    }

}




   package planets;

public class SolarSystem {

    private Planet[]planets;
    private int position = 0;
    Planet[]moons;

 public SolarSystem(int size) {  
     planets = new Planet[size];
 }

public void add(Planet planet) {
    planets[position] = planet;
    position++;

}

public int sum(Planet moons) {
    int sum = 0;
    for(int i = 0; i < moons(); i++)
        sum += moons[]; 
     }
     return sum;
}

public String toString(){
    String result = "";
    for(int i = 0; i < planets.length; i++){
        result += planets[i].toString(); 

    }
    System.out.println("You Have " + position + " Planets In Your Solar System");

    return result;  

}
}

package planets;

public class Driver {

    public static void main(String[]args) {

        Planet mercury  = new Planet ("Mercury", 0);

        Planet venus = new Planet ("Venus", 0);

        Planet earth = new Planet ("Earth", 1);

        Planet mars = new Planet ("Mars", 2);

        Planet jupiter = new Planet ("Jupiter", 67);

        Planet saturn = new Planet ("Saturn", 62);

        Planet uranus = new Planet ("Uranus", 27);

        Planet neptune = new Planet ("Neptune", 14);

        Planet pluto = new Planet ("Pluto", 5);

        SolarSystem solarSystem = new SolarSystem(9);       

        solarSystem.add(mercury);
        solarSystem.add(venus);
        solarSystem.add(earth);
        solarSystem.add(mars);
        solarSystem.add(jupiter);
        solarSystem.add(saturn);
        solarSystem.add(uranus);
        solarSystem.add(neptune);
        solarSystem.add(pluto);



        System.out.println(solarSystem);

    }

}

2 个答案:

答案 0 :(得分:1)

使用类似下面的内容,但我还没有测试过。

public int sum(Planet[] planets) {
    int sum = 0;
    for(Planet planet : planets)
        sum += planet.moons[]; 
     }
     return sum;
}

您应该传递Planet类型的对象数组,然后从每个moons获取Planet字段,并将其添加到总和中。

作为建议,由于您已经将Planet个对象添加到SolarSystem中的数组中,只需向该类添加getPlanets()方法,以便您可以获取该数组如果需要,还可以PlanetSolarSystem个对象。

public Planet[] getPlanets()
{
   return planets;
}

另外,不要使用函数名称sum使用类似totalMoons()的内容。

答案 1 :(得分:1)

只需将所有内容保留原样并使用此实际工作的java代码进行求和

public int sum(Planet[] planets) {
    int sum = 0;
    for(Planet planet : planets){
        sum += planet.moons; 
    }
    return sum;
}