Results 1 to 8 of 8
  1. #1
    smallmos1 is offline Member
    Join Date
    Sep 2010
    Posts
    23
    Rep Power
    0

    Default inner classes problem

    please have a look and see if you can help.

    question:
    You are required to create a class SolarSystem that will define an object containing a variable number of planets. You will put the definition for the class Planet inside the definition of the class SolarSystem.

    When a SolarSystem object is being created, the user specifies the name of the solar system and the number of planets in the solar system. The Planet objects should be stored in an array.

    When creating a Planet object the user specifies the name of the planet and its distance
    from its Sun in millions of miles. For example in our solar system, Earth is 93 million miles from the Sun. This would be stored as 93. The array of Planet objects is filled by allowing the user to enter the names of the planets and their distance from the Sun, at the keyboard.

    Include a printDetails() method to display the details of the Solar System and its Planets.

    Create a test class that creates an instance of SolarSystem called Our Solar System. Our Solar System has nine planets. (For the CA you can assume that Pluto is still a planet).
    Call the printDetails() method.


    Java Code:
    package Q1;
    
    import java.util.*;
    
    public class SolarSystem 
    {
    	static Scanner sc = new Scanner(System.in);
    	static Planet[] planets;
    	
    	int numPlanets;
    	static String SSName;
    	
    	public SolarSystem()
    	{
    		System.out.println("Name of solar system?");
    		SSName = sc.next();
    		sc.nextLine();
    		System.out.println("How many planets in your solar system?");
    		numPlanets = sc.nextInt();
    		sc.nextLine();
    		planets = new Planet[numPlanets];
    	}
    	
    	static class Planet
    	{
    		String planetName;
    		int disFromSun; //millions of miles
    		
    		public Planet()
    		{
    			for(int i = 0; i < planets.length; i++ )
    			{
    				System.out.println("What is the name of planet number  " + (i+1));
    				planetName = sc.next();
    				System.out.println("How far is it from the sun?");
    				disFromSun = sc.nextInt();
    			}
    		}
    		
    		public static void printDetails()
    		{
    			System.out.println("The name of the solar system is " + SolarSystem.SSName);
    			for(int i = 0; i < planets.length; i++)
    			{
    				System.out.println("Planet name: " + planets[i].planetName + "\nDistance from Sun " + planets[i].disFromSun);
    			}
    		}
    	}
    }
    test class

    Java Code:
    package Q1;
    
    import Q1.SolarSystem.Planet; //did this as a prompt from eclipse, though i think it isn't needed??
    
    public class TestSolarSytem 
    {
    	public static void main(String[] args) 
    	{
    		SolarSystem ourSolarSystem = new SolarSystem();
    		Planet ourPlanets = new Planet();
    		
    		//SolarSystem.Planet planets = ourSolarSystem.new Planet(); -----> get an error when i try that:
    											//Illegal enclosing instance specification for type SolarSystem.Planet
    		
    		//I've also tried ourPlanets.printDetails();
    		//and Planet.printDetails();
    	}
    
    }
    compiler error:
    Name of solar system?
    The milky way
    How many planets in your solar system?
    1
    What is the name of planet number 1
    Earth
    How far is it from the sun?
    78
    The name of the solar system is The
    Exception in thread "main" java.lang.NullPointerException
    at Q1.SolarSystem$Planet.printDetails(SolarSystem.jav a:45)
    at Q1.TestSolarSytem.main(TestSolarSytem.java:11)


    so its working up until it has to print the first system.out.println in the printDetails method, then the error occurs.

    Any help appreciated.

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,023
    Blog Entries
    7
    Rep Power
    20

    Default

    Why all the static stuff in your code? That way you can only have one solar system and the planets all have to remember around what start they're orbiting. Remove all the static stuff (including the static class Planet, make it a real inner class). That way you can create as many stars as you want and make your planets circle around (single) stars and they 'know' around what star they're circling. A star still needs to know about its planets.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  3. #3
    j2me64's Avatar
    j2me64 is offline Senior Member
    Join Date
    Sep 2009
    Location
    Zurich, Switzerland
    Posts
    962
    Rep Power
    5

    Default

    you create an array of objects of the type Planet but the code is never assigning a new Planet to the array, so all your elements in the array of Planet will be null. inside the class SolarSystem you should use a loop like

    Java Code:
    		for (int i = 0; i < numPlanets; i++) {
    			planets[i] = new Planet();
    		}

    for assigning objects to your array and delete this loop from the Planet class.

  4. #4
    smallmos1 is offline Member
    Join Date
    Sep 2010
    Posts
    23
    Rep Power
    0

    Default

    thanks for the replies.

    I removed static stuff, only reason i had it in was because the

    System.out.println("The name of the solar system is " + SolarSystem.SSName);

    line of code, when using the 'SolarSystem'.SSName, prompted to make those things static.

    my test class now looks like this:
    Java Code:
    package Q1;
    
    public class TestSolarSytem 
    {
    	public static void main(String[] args) 
    	{
    		SolarSystem ourSolarSystem = new SolarSystem();
    		SolarSystem.Planet ourPlanets = ourSolarSystem.new Planet();
    		ourPlanets.printDetails();
    	}
    
    }
    but i'm getting an error in this line:
    Java Code:
    SolarSystem.Planet ourPlanets = ourSolarSystem.new Planet();
    and the error is 'Illegal enclosing instance specification for type SolarSystem.Planet'. Could anyone tell me what this means?

    I copied the format (below) from another exercise i did and it worked fine...
    Java Code:
    Outside.Inside inside = outside.new Inside(9);

  5. #5
    j2me64's Avatar
    j2me64 is offline Senior Member
    Join Date
    Sep 2009
    Location
    Zurich, Switzerland
    Posts
    962
    Rep Power
    5

    Default

    Quote Originally Posted by smallmos1 View Post
    Java Code:
    package Q1;
    
    public class TestSolarSytem 
    {
    	public static void main(String[] args) 
    	{
    		SolarSystem ourSolarSystem = new SolarSystem();
    		SolarSystem.Planet ourPlanets = ourSolarSystem.new Planet();
    		ourPlanets.printDetails();
    	}
    
    }
    but i'm getting an error in this line:
    Java Code:
    SolarSystem.Planet ourPlanets = ourSolarSystem.new Planet();
    and the error is 'Illegal enclosing instance specification for type SolarSystem.Planet'. Could anyone tell me what this means?

    an inner class can't exist without the outer class, except you declare the inner class as static.

    i made some modifications to your code: inside the class Planet only its members are readed. because the array of Planet is declared inside the class SolarSystem also all planets are instantiate inside this class. Also the method printDetails belongs to the class Solarsystem because it prints all planets details inside the solarsystem. here is the code:

    Java Code:
    package Q1;
    
    import Q1.SolarSystem.Planet; //did this as a prompt from eclipse, though i think it isn't needed??
    
    public class TestSolarSystem 
    {
    	public static void main(String[] args) 
    	{
    		SolarSystem ourSolarSystem = new SolarSystem();
    		ourSolarSystem.printDetails();
    	}
    
    }
    Java Code:
    package Q1;
    
    import java.util.*;
    
    public class SolarSystem {
    	static Scanner sc = new Scanner(System.in);
    	static Planet[] planets;
    
    	int numPlanets;
    	static String SSName;
    
    	public SolarSystem() {
    		System.out.print("Name of solar system? ");
    		SSName = sc.next();
    		sc.nextLine();
    		System.out.print("How many planets in your solar system? ");
    		numPlanets = sc.nextInt();
    		sc.nextLine();
    		planets = new Planet[numPlanets];
    		for (int i = 0; i < planets.length; i++) {
    			planets[i] = new Planet(i);
    		}
    	}
    	
    	public static void printDetails() {
    		System.out.println("The name of the solar system is "
    				+ SolarSystem.SSName);
    		for (int i = 0; i < planets.length; i++) {
    			System.out.println("Planet name: " + planets[i].planetName
    					+ "\nDistance from Sun " + planets[i].disFromSun);
    		}
    	}
    
    	static class Planet {
    		String planetName;
    		int disFromSun; // millions of miles
    
    		public Planet(int i) {
    			System.out.print("What is the name of planet number  " + (i + 1) + "? ");
    			planetName = sc.next();
    			System.out.print("How far is it from the sun? ");
    			disFromSun = sc.nextInt();
    		}
    	}
    }

  6. #6
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,023
    Blog Entries
    7
    Rep Power
    20

    Default

    Why is that Planet class still static?

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  7. #7
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,450
    Rep Power
    19

    Default

    Apart from the Scanner why is any of that static?

  8. #8
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,023
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by Tolls View Post
    Apart from the Scanner why is any of that static?
    Just because astronomy is one of my hobby's and because I had nothing better to do I crafted the following data class:

    Java Code:
    class SolSysData {
    	public static String star = "Sun";
    	public static String[] planets = { "Mercury", "Venus", "Earth", "Mars",
    			"Ceres", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto",
    			"Haumea", "Makemake", "Eris" };
    
    	public static long[] distance = { 57909175L, 108208930L, 149597890L,
    			227936640L, 413781779L, 778412020L, 1426725400L, 2870972200L,
    			4498252900L, 5906380000L, 6482824563L, 6850236980L, 10123004980L };
    
    	public static String[][] moons = {
    			{},
    
    			{},
    
    			{ "Moon" },
    
    			{ "Phobos", "Deimos" },
    
    			{},
    
    			{ "Io", "Europa", "Ganymede", "Callisto", "Amalthea", "Himalia",
    					"Elara", "Pasiphae", "Sinope", "Lysithea", "Carme",
    					"Ananke", "Leda", "Thebe", "Adrastea", "Metis",
    					"Callirrhoe", "Themisto", "Megaclite", "Taygete",
    					"Chaldene", "Harpalyke", "Kalyke", "Iocaste", "Erinome",
    					"Isonoe", "Praxidike", "Autonoe", "Thyone", "Hermippe",
    					"Aitne", "Eurydome", "Euanthe", "Euporie", "Orthosie",
    					"Sponde", "Kale", "Pasithee", "Hegemone", "Mneme", "Aoede",
    					"Thelxinoe", "Arche", "Kallichore", "Helike", "Carpo",
    					"Eukelade", "Cyllene", "Kore", "Herse", "S/2003 J2",
    					"S/2003 J3", "S/2003 J4", "S/2003 J5", "S/2003 J9",
    					"S/2003 J10", "S/2003 J12", "S/2003 J15", "S/2003 J16",
    					"S/2003 J18", "S/2003 J19", "S/2003 J23" },
    
    			{ "Mimas", "Enceladus", "Tethys", "Dione", "Rhea", "Titan",
    					"Hyperion", "Iapetus", "Erriapus", "Phoebe", "Janus",
    					"Epimetheus", "Helene", "Telesto", "Calypso", "Kiviuq",
    					"Atlas", "Prometheus", "Pandora", "Pan", "Ymir", "Paaliaq",
    					"Tarvos", "Ijiraq", "Suttungr", "Mundilfari", "Albiorix",
    					"Skathi", "Siarnaq", "Thrymr", "Narvi", "Methone",
    					"Pallene", "Polydeuces", "Daphnis", "Aegir", "Bebhionn",
    					"Bergelmir", "Bestla", "Farbauti", "Fenrir", "Fornjot",
    					"Hati", "Hyrrokkin", "Kari", "Loge", "Skoll", "Surtur",
    					"Greip", "Jarnsaxa", "Tarqeq", "Anthe", "Aegaeon",
    					"S/2004 S7", "S/2004 S12", "S/2004 S13", "S/2004 S17",
    					"S/2006 S1", "S/2006 S3", "S/2007 S2", "S/2007 S3",
    					"S/2009 S1" },
    
    			{ "Cordelia", "Ophelia", "Bianca", "Cressida", "Desdemona",
    					"Juliet", "Portia", "Rosalind", "Mab", "Belinda",
    					"Perdita", "Puck", "Cupid", "Miranda", "Francisco",
    					"Ariel", "Umbriel", "Titania", "Oberon", "Caliban",
    					"Stephano", "Trinculo", "Sycorax", "Margaret", "Prospero",
    					"Setebos", "Ferdinand" },
    
    			{ "Triton", "Nereid", "Naiad", "Thalassa", "Despina", "Galatea",
    					"Larissa", "Proteus", "Halimede", "Psamathe", "Sao",
    					"Laomedeia", "Neso" },
    
    			{ "Charon", "Hydra", "Nix" },
    
    			{ "Hi'aka", "Namaka" },
    
    			{},
    
    			{ "Dysnomia" } };
    }
    Note that I added a few dwarf planets and also note that I knew all those moons by head ;-) The distances are in kilometres and the last three distances are estimations for the Plutoids. The following class builds a representation of our solar system and prints its data:

    Java Code:
    public class SolarSystem {
    
    	private String name;
    	private List<Planet> planets= new ArrayList<Planet>();
    	
    	public SolarSystem(String name) { this.name= name; }
    
    	public String getName() { return name; }
    	public List<Planet> getPlanets() { return planets; }
    	
    	public class Planet {
    		
    		private String name;
    		private long distance;
    		
    		private List<Moon> moons= new ArrayList<Moon>();
    		
    		public Planet(String name, long distance) { 
    			
    			this.name= name; 
    			this.distance= distance;
    			
    			planets.add(this); 
    		}
    
    		public String getName() { return name; }
    		public long getDistance() { return distance; }
    		public List<Moon> getMoons() { return moons; }
    		
    		public class Moon {
    			
    			private String name; 
    			
    			public Moon(String name) { this.name= name; moons.add(this); }
    			
    			public String getName() { return name; }
    
    			public String toString() { return name+" ("+Planet.this+")"; }
    		}
    		
    		public String toString() { return name+"["+distance+"] ("+SolarSystem.this+")"; }
    	}
    	
    	public String toString() { return name; }
    	
    	public static void main(String[] args) {
    		
    		SolarSystem star= new SolarSystem(SolSysData.star);
    		
    		for (int i= 0; i < SolSysData.planets.length; i++) {
    			SolarSystem.Planet planet= star.new Planet(SolSysData.planets[i], SolSysData.distance[i]);
    			
    			for (int j= 0; j < SolSysData.moons[i].length; j++)
    				planet.new Moon(SolSysData.moons[i][j]);
    		}
    	
    		System.out.println(star+":");
    
    		for (SolarSystem.Planet planet: star.getPlanets()) {
    			System.out.println("\t"+planet+":");
    			
    			for (SolarSystem.Planet.Moon moon : planet.getMoons())
    				System.out.println("\t\t"+moon);
    			System.out.println();
    		}
    	}
    }
    If we add more data for the planets (source: NASA) we could actually draw our entire solar system and make it move ;-)

    kind regards,

    Jos
    Last edited by JosAH; 11-18-2010 at 03:31 PM.
    cenosillicaphobia: the fear for an empty beer glass

Similar Threads

  1. Problem with multiple string in classes
    By sjaakie in forum New To Java
    Replies: 3
    Last Post: 10-10-2010, 02:48 PM
  2. problem with using classes and output
    By sjaakie in forum New To Java
    Replies: 3
    Last Post: 10-10-2010, 01:56 PM
  3. Problem to organize my code in classes
    By ze snow in forum New To Java
    Replies: 4
    Last Post: 02-23-2010, 04:28 AM
  4. Passing values between classes problem.
    By alin_ms in forum New To Java
    Replies: 8
    Last Post: 12-12-2008, 06:49 PM
  5. [SOLVED] Problem with extending classes...
    By Bizmark in forum New To Java
    Replies: 4
    Last Post: 04-07-2008, 11:21 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •