我有9个数字的字符串。我想把它们加在一起。我不知道我错过了什么
写这个的正确方法是什么?卫星是在行星类中定义的,这是太阳系类:卫星掌握着每颗行星的数量。
好的,我贴了完整的代码。在驱动程序中,我把行星和它们有多少颗卫星相加。我想把所有的卫星都添加到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);
}
}
发布于 2014-02-28 00:21:53
只需保留一切,并使用实际工作的java代码作为sum。
public int sum(Planet[] planets) {
int sum = 0;
for(Planet planet : planets){
sum += planet.moons;
}
return sum;
}
发布于 2014-02-28 00:13:46
使用下面这样的东西,虽然我还没有测试它。
public int sum(Planet[] planets) {
int sum = 0;
for(Planet planet : planets)
sum += planet.moons[];
}
return sum;
}
您应该传递一个Planet
类型的对象数组,然后从每个Planet
中获取moons
字段,并将其添加到sum中。
作为建议,既然您已经将Planet
对象添加到SolarSystem
中的数组中,只需向该类添加一个getPlanets()
方法,以便在需要时也可以从SolarSystem
类获得Planet
对象的数组。
public Planet[] getPlanets()
{
return planets;
}
另外,不要使用函数名,因为sum
使用类似于totalMoons()
的东西。
https://stackoverflow.com/questions/22083494
复制相似问题