Creating an array of objects

Hey,
I basically have two classes and am trying to create an array of one class in the sub class. My code keeps coming up with <identifier> expected on complie:
Main Class
import java.util.ArrayList;
import java.io.*;
* @author David Bainbridge
* @Date 12/02/07
public class Main {
         public ArrayList<City>ListOfCities;
public static void main(String[] arguments) {
     Main.newcity();
     public Main() {
     ListOfCities = new ArrayList<City>(); //this creates an array which stores all instances of the cities.
     public static void newcity() {
          String Name = "Lincoln";
          String Lat = "10";
          String Long = "11";         
          ListOfCities.add(new City(Name, Lat, Long)); 
          Lincoln.displaycity();
}City Class
  * The City class represents a City.
  * @author David Bainbridge
  * @Date 13/02/07
public class City {
     private String Name;
     private String Latitude;
     private String Longitude;
      * Constructor for the City.
     public City(String cityName, String cityLat, String cityLong) {
          Name = cityName;
          Latitude = cityLat;
          Longitude = cityLong;          
      * Display the current City.
public void displaycity() {
          System.out.println("Name: " + Name);
          System.out.println("Latitude: " + Latitude);
          System.out.println("Longitude: " + Longitude);
}

Thanks JJCoolB but neither worked!
I have rejigged my code:
import java.util.ArrayList;
import java.io.*;
* @author David Bainbridge
* @Date 12/02/07
public class Main {
         public static ArrayList<City>ListOfCities;
public static void main(String[] arguments) {
     ListOfCities = new ArrayList<City>(); //this creates an array which stores all instances of the cities.
     Main.newcity();
     public static void newcity() {
          String Name = "Lincoln";
          String Lat = "10";
          String Long = "11";         
          ListOfCities.add(new City(Name, Lat, Long)); 
          Lincoln.displaycity();
}I get two complie errors with it one says:
public static ArrayList<City>ListOfCities; - <identifier> expected
ListOfCities = new ArrayList<City>(); //this creates an array which stores all instances of the cities. - '(' or '[' expected.
Thanks in advance for any help people!

Similar Messages

  • Formatted .data file, reading in and creating an array of objects from data

    Hi there, I have written a text file with the following format;
    List of random personal data: length 100
    1 : Atg : Age 27 : Income 70000
    2 : Dho : Age 57 : Income 110000
    3 : Lid : Age 40 : Income 460000
    4 : Wgeecnce : Age 43 : Income 370000
    and so on.
    These three pieces of data, Name,Age and Income were all generated randomly to be stored in an array of objects of class Person.
    Now what I must do is , read in this very file and re-create the array of objects that they were initially written from.
    I'm totally lost on how to go about doing this, I have only been learning java for the last month so anyone that can lend me a hand, that would be superb!
    Cheers!

    Looking at you other thread, you are able to create the code needed - so what's the problem?
    Here's an (not the only) approach:
    Create an array of the necessary length to hold the 3 variables, or, if you don't know the length of the file, create a class to contain the data. Then create an ArrayList to hold an instance of the class..
    Use the Scanner class to read and parse the file contents into the appropriate variables.
    Add each variable to either the array, or to an instance of the class and add that instance to the arraylist.

  • Creating an arrays of objects from a class

    I was wondering does any one know how to create an array of objects from a class?
    I am trying to create an array of objects of a class.
    class name ---> Class objectArray[100] = new Class;
    I cant seem to make a single class but i need to figure out how to create an array of objects.
    I can make a normal class with Class object = new Class

    There are four lines of code in your for-loop that actually do something:
    for(index = 0; index < rooms.length; index++) {
    /*1*/  assignWidth.setWidth(Double.parseDouble(in.readLine()));
    /*2*/  rooms[index] = assignWidth;
    /*3*/  assignLength.setWidth(Double.parseDouble(in.readLine());
    /*4*/  rooms[index] = assignLength;
    }1.) Sets the width of an object, that has been instantiated outside the loop.
    2.) assigns that object to the current position in the array
    3.) Sets the width of a second object that has been instantiated outside the loop
    4.) assigns that other object to the current position in the array
    btw.: I bet you meant "assignLength.setLength(Double.parseDouble(in.readLine());" in line 3 ;)
    Since each position in an array can only hold one value, the first assignment (line 2) is overwritten by the second assignment (line 4)
    When I said "construct a new room-object and assign it to rooms[index]" I meant something like this:
    for(index = 0; index < rooms.length; index++) {
        Room aNewRoom = new Room();
        aNewRoom.setWidth(Double.parseDouble(in.readLine()));
        aNewRoom.setLength(Double.parseDouble(in.readLine());
        rooms[index] = aNewRoom;
    }1.) Constructs a new Object in every iteration of the for-loop. (btw: I don't know what kind of objects you're using, so this needs most likely modification!!)
    2.) set the width of the newly created object
    3.) set the length of the newly created object
    4.) assign the newly created object to the current position in the array
    -T-
    btw. this would do the same:
    for(index = 0; index < rooms.length; index++) {
        rooms[index] = new Room();
        rooms[index].setWidth(Double.parseDouble(in.readLine()));
        rooms[index].setLength(Double.parseDouble(in.readLine());
    }but be sure you understand it. Your teacher most likely wants you to explain it ;)

  • Creating an array of objects of a class known ONLY at RUNTIME

    I have a method in a class which expects an array of objects of particular type (say A) as its only argument. I 'invoke' this method using reflection. I have the instances of the class A stored in a Vector. When I do 'toArray' on this vector, what I get back is an array of Objects and not an array of objects of A. I assign this array to the zeroth element of another Object array and pass that array as a second argument to the 'invoke' method. Of course, it throws an Exception saying - argument types mismatch. Because I am sending an array of Objects to a method expecting an array of objects of A. My problem is I don't know A until runtime. So I have to handle whatever I am getting back after doing 'toArray' on a vector as a Generic Object. I know there's another version of 'toArray' in the Vector class. But it's API documentation didn't help a lot.
    Can anybody please help me solve this problem? Any sort of hints/code snippet would be of great help.
    Does the above description makes any sense? If not, please let me know. I would try to illustrate it with a code sample.
    Thanks a lot in advance.

    Sorry, for the small typo. It is -
    clazz[] arr = (clazz [])java.lang.reflect.Array.newInstance(clazz, n);
    instead
    Thanks for the reply. I could do this. But I am
    getting a handle to the method to be 'invoke'd by
    looking at the types of the parameters its
    expecting(getParameterTypes). So I can't change it to
    accept an array of Generic Objects.
    I looked at the java.lang.reflect.Array class to do
    this. This is what I am trying to do-
    String variableName is an input coming into my
    program.
    n is the size of the array I'm trying to create.
    Class clazz = Class.forName(variableName);
    clazz[] arr = (clazz
    [])java.lang.reflect.newInstance(clazz, n);
    According to Reflection API, it should work, right?
    But compiler yells at me saying 'class clazz not
    found'.
    Any suggestions/hints/help?
    Thanks, again.

  • How to create an Array of Object

    Is this correct:
    Object[] anArray = new Object[5];
    Thanks.

    Your code will create an array of 5 null references to class Object. After that line you could code:anArray[0] = new Integer(5);- or -
    Object x = anArray[1];but if you code:anArray[3].DoSomething();and have not initialized anArray[3], you will get a NullPointerException.
    Doug

  • Creating an array of objects sets them all to null?

    I am using the following code:
    public class PlayerTest {
        public static void main(String[] args) {
            Player[] p = new Player[1];
            System.out.println(p[0].getId());
    }and for the 'Player' object:
    public class Player {
        int id;
        String name;
        int prediction;
        int score;
        public Player() {
            this.name = "a";
            this.score = -1;
            this.id = genRanId();
            this.prediction = -1;
    ...and, when i try to execute the "PlayerTest" class, i get the error:
    Exception in thread "main" java.lang.NullPointerException
            at PlayerTest.main(PlayerTest.java:5)I think this is because when the array of player objects is created, they are all set to null, and the fields are not created. How do i get the program to initialise the fields in each player object of the array?
    Creating the array of Player objects doesnt seem to use the constructor for the player class like creating an indivdual one does for some reason, as if i create a single element, instead of an array of them, it works fine....
    Please help!

    Yes you are quite right they are null by default (that is nothing is assigned to the array of pointers you have created) you will have t initialise the array the array
            Player[] p = new Player[1];
            for(int i=0;i<p.length;i++)p[i] = new Player();
        //or you can do
       Player[] p = {new Player(),new Player()};(IMHO) Its pointless having an array like this with identical objects you are betteroff instantiating the Person class using a constructor that takes some initial parameters however it is up to you.
    Good luck
    Wiraj

  • Create an array of objects

    i have to write a program with 3 classes, Student, Coarse, and Main.
    Coarse class has 3 instance variables, with the constructor:
    public Coarse(String symbol, String name, int credit)Student class has 3 instance variables plus one method, one of these variables is an array of class Coarse, if i write a constructor of Coarse-class in Student, i would limit the number of coarses to one.
    Coarse coarse=new Coarse("CMPE112", "OOP", "3");i want the student to input all the coarses he signed in???

    noowa wrote:
    i want the student to input all the coarses he signed in???How do you want them to input their courses? If this is a dynamically-sized array, then instead of using an Array, go for an ArrayList. Then find some way to get user input (if that's what you wanted) and then instantiate new course objects into the ArrayList.
    Arrays: http://java.sun.com/docs/books/tutorial/reflect/special/index.html
    Lists: http://java.sun.com/docs/books/tutorial/collections/implementations/list.html
    ArrayList: http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html
    As for input, there are many, many options. Common ones are use the BufferedReader, InputStreamReader, and Scanner classes.
    There are some solutions here: http://forum.java.sun.com/thread.jspa?threadID=555025&messageID=2724272
    I'm not fully comprehending your question. Care to give some surrounding code or information?

  • Creating array of objects of JLabel , JTextField type

    hello,
    I wanted to create an array of objects of JLabel class. I wrote and complied the following lines. it was successfully compiled but during execution it showed - 'start: applet not initialized' on the applet's window. What wrong have I done and how can I get rid of that?
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    /*<html>
    <applet code="test.class" width=200 height=300>
    </applet>
    </html> **/
    public class test extends JApplet
         Container c = getContentPane();
         JLabel lb[];
         public void init()
                   for( int i = 0; i < 10; i++ )
                   lb[i] = new JLabel( "Line" + i );
                   c.add( lb[i] );
    }

    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    /*<html>
    <applet code="test.class" width=200 height=300>
    </applet>
    </html> **/
    public class test extends JApplet
         Container c = getContentPane();
         JLabel lb[] = new JLabel[10];
         public void init()
                   for( int x = 0; x < 10; x++ )
                   lb [x]= new JLabel( "Line" + x );
                   c.add( lb );
    // showing applet not initiliazed
    // generating nullPointerException
    // please helpLast post, thats a promise!!! :-)Still wrong. See corrections in 'for' loop. :)

  • Array of Object Refs

    I am doing exercises in a book (a couple books) to learn Java. I am a procedural pgmr and want to learn Java.
    Question 3 in Chapter 4 says:
    Create an array of object references of the class you created in Exercise 2, but don't actually create objects to assign into the array. When you run the program, notice whether the initialization messages from the constructor calls are printed.
    In exercise 2, I created an created an overloaded constructor. There are two constructors one that takes an argument and one that doesn't. I think I understand that I am being asked to look to see the values of the variables before the object is actually created but after initialization.
    My question is that I am not sure I understand what is being asked in question 3. I have to create an array of object references. I understand object references to be the varable names that hole the contents of the object. I don't understand what I am supposed to put into each (the two) elements of the array.
    Here is program written for exercise 2:
    //: c04:J402.java
    /* This has overloaded constructors. However, the argument must be given. Without it, there is an exception at runtime. */
    class Bird {
    Bird() {
    System.out.println("The object is an egg");
    Bird(String age) {
    System.out.println("The object is " + age + " months old");
    public class J402 {
    public static void main(String[] args) {
    String age = args[0];
    new Bird(age);
    } ///:~
    Thank you so much for any help.

    My question is that I am not sure I understand what is
    being asked in question 3. I have to create an array
    of object references. I understand object references
    to be the varable names that hole the contents of the
    object. I don't understand what I am supposed to put
    into each (the two) elements of the array.
    You need to make three different concepts clear to yourself: objects, object references, and reference variables.
    Objects are objects are objects. They are self contained entities that live somewhere in the memory. But, as you can't manipulate the memory directly (there are many good reasons for that), you can't manipulate objects directly.
    To get to objects you need references (or pointers). A reference is like a memory address. It normally points to the memory location of an object, but if the reference can also be a special 'null' reference that doesn't point to any object (or to every possible object, depending on how you want to look at it). The JVM takes care of talking to the underlaying object through the reference.
    An object can have many references pointing to it but a reference can point to only one object (or no / any object in the case of a null reference).
    Reference variables, then, are the ones you have in source code. Here's an example of a reference variable:Bird tweety;
    tweety = new Bird("I thought I saw a pussy cat!");(given a hypotetical class that can take a String object as an argument to the constructor)
    "tweety" is a reference variable. A reference variable is a variable that can hold a reference -- surprise! :). If not set to any particular reference, it's value may be null. If you now do something likeBird bird2 = tweety;
    tweety = new Bird();you first define a new ref. variable "bird2" and set its value to tweety's ref. Then you reset the var. tweety to point to a new Bird object. What happens to bird2? Nothing!! ... but if instead of "tweety = new Bird();" you had written "tweety.setChirp("TWEET!!!");" and then called bird2.chirp(), it would have chirped with "TWEET!!!" because the references of bird2 and tweety point to the same object.
    But, you can have references outside reference variables. In reference arrays (or "object arrays", the terminology can be confusing), for instance. Then, the codeBird[] flock = new Bird[2];0) Creates, allocates and initializes a new reference array object.
    1) Creates a new reference variable called "flock" and assigns it to a reference that points to the object that was created in 0).
    2) Creates 2 more references to Bird objects, initially set to null. No further objects are created. These references can be used like reference variables through flock[0] and flock[1].
    (not necessarily in this order)
    Now this should answer the excersise 3. The references of flock[0] and flock[1] are left as null and they don't point to any objects - They will only if you do something like "flock[0] = new Bird("chirp!");" or "flock[1] = tweety;"

  • An array of objects

    Hi,
    I'm having trouble creating an array of objects to store data I'm reading in from a text file.
    I have created a class called mssg, and as I read each line of the textfile in, I've created a method called setMsg that I'm using to populate the mssg object I've created.
    This works fine when I use this method on a single instance of a mssg object, but when I try to use the same code on a mssg object that's part of an array, I get an exception (and one that doesn't have any friendly error text)
    mssg ms = new mssg();  //this works as expected
    mssg msgs[] = new mssg [msgCounter]; //I believe the exception relates to how I'm declaring the array of objects here, but the exception doesn't occur until I try to assign data to an element of the arrayThe lines below are where the problem becomes apparent. The first object 'ms' gets assigned its values as I'd expect, however, the line below that tries to assign values to a mssg object in the msgs array, and I get an exception immediately.
    ms.setMsg(currMsg,mDt,mTm,mDir,mData);
    msgs[currMsg].setMsg(currMsg,mDt,mTm,mDir,mData);Can anyone tell me what I'm doing wrong in terms of declaring/assigning values to an array of objects?

    It's the following error: java.lang.NullPointerException
    Full error text if I take my code out of a try/catch loop is:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
            at FIXparserUI.jMenuLoadActionPerformed(FIXparserUI.java:301)
            at FIXparserUI.access$100(FIXparserUI.java:20)
            at FIXparserUI$3.actionPerformed(FIXparserUI.java:129)
            at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
            at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
            at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
            at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
            at javax.swing.AbstractButton.doClick(AbstractButton.java:357)
            at javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:1170)
            at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:1211)
            at java.awt.Component.processMouseEvent(Component.java:6038)
            at javax.swing.JComponent.processMouseEvent(JComponent.java:3260)
            at java.awt.Component.processEvent(Component.java:5803)
            at java.awt.Container.processEvent(Container.java:2058)
            at java.awt.Component.dispatchEventImpl(Component.java:4410)
            at java.awt.Container.dispatchEventImpl(Container.java:2116)
            at java.awt.Component.dispatchEvent(Component.java:4240)
            at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
            at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
            at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
            at java.awt.Container.dispatchEventImpl(Container.java:2102)
            at java.awt.Window.dispatchEventImpl(Window.java:2429)
            at java.awt.Component.dispatchEvent(Component.java:4240)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
            at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
            at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)at the point that the following line of code is run:
    msgs[currMsg].setMsg(currMsg,mDt,mTm,mDir,mData);msgCounter is used to count the number of lines in the file (about 2300)
    I had hoped that what I was doing with this line:
    mssg msgs[] = new mssg [msgCounter];was create 2300 empty mssg records, ready to be populated from each line of data, however I have the feeling you're going to tell me I'm wrong.

  • How to create an array using reflection.

    How to create an array using reflection.
    I want to achive something like this,Object o;
    o = (Object)(new TestClass[10]);but by use of reflection.
    To create a single object is simple:Object o;
    o = Class.forName("TestClass").newInstance();But how do I create an array of objects, when the class of objects is known only by name? (Can't use Object[] because even though an Object[] array can be filled with "TestClass" elements only, it Cannot be casted to a TestClass[] array)
    Anybody knows?":-)
    Ragnvald Barth
    Software enigneer

    Found it!
    the java.lang.reflect.Array class solves it!
    Yes !!!

  • Plz help!! array of object (for search)

    i've got few questions of array of object
    1-how to search for a price that is greater than 300 in the array of object
    and how to list all of them?
    2- how to search for the smallest price in the array of object, and how to list?
    can anyone provde a java code for me:P?
    but plz don't too complex
    coz i'm a learner of javaT_T

    _< i still can't understand, and dunno how to change into the code that i needand you guyz help me change it?
    /*wirte the driver program which will define and create an array of
    objects instantiated from the class WaterBill
    Create Accessor and Mutator methods to get/set data from the class.
    write code within the driver method to perfrom the following:
    a) The final total of funds
    b) To search for accounts greater than $300 in the array of objects,
         and list all the customer details
    c)To search for the lowest bill in the array of objects, and list
    those customer dtails
    Class definitions and Objects  using price
    import java.text.*;
    import javax.swing.JOptionPane;
    public class Pre_pb3
         public static void main(String []args)
              int  TTc=0;
              int accNum[]=new int[20];
              String name[]=new String[20], output, stans, display; //stAccNum, stUsage, stTTc;
              double usage[]=new double[20];
              double TTa=0.0;
              double price[]=new double[20];
              char ans;
              double acctG,lowest;
              int i=0;
              waterBill MYwaterBill = new waterBill();
              ans='Y';
              while (!(ans=='N'))
                   name=inputName();
                   accNum[i]=inputAccNum();
                   usage[i]=inputUsage();
                   price[i]=calculateAmountOwing(usage[i]);
                   TTa=MYwaterBill.TTaPrice(price[i]);
                   output=MYwaterBill.outputInfo(name[i], accNum[i], usage[i], price[i]);
                   waterBill MYwaterBill2= new waterBill(name[i], accNum[i],usage[i], price[i]);     
                   stans=JOptionPane.showInputDialog("Do you wanna continue?, (Y)es, (N)o");
                   stans = stans.substring(0, 1);
                   stans=stans.toUpperCase();
                   ans=stans.charAt(0);
                   TTc++;     
              MYwaterBill.outputoutput(TTc, TTa);
              MYwaterBill.findGreat();     //b)
              MYwaterBill.searchDetail();     //c)
              System.exit(0);                                                  
         public static String inputName()
                   String name;
                   name=JOptionPane.showInputDialog("Enter Name ");
                   return name;
         public static int inputAccNum()
              int accNum;
              String stAccNum;
              stAccNum=JOptionPane.showInputDialog("Enter Account Number");
              accNum=Integer.parseInt(stAccNum);
              return accNum;
         public static double inputUsage()
              double usage;
              String stUsage;
              stUsage=JOptionPane.showInputDialog("Enter Water Usage");
              usage=Double.parseDouble(stUsage);
              if (!(usage>=0 && usage<=99999999))
                   System.out.println("water useage is invalid");
                   System.exit(0);
              return usage;
         public static double calculateAmountOwing(double usage)
              double price=0.0;
              if (usage>=0)
                   if (usage<=10000)
                        price=(10000/10)*0.01;
                   else if (usage>10000)
                        price=((10000/10)*0.01)+(((usage-10000)/10)*0.02);
              else
                        System.out.println("Error of usage");
                   return price;
    class waterBill
         private static     int TTc=0 ,accNum=0;
         private static String name, stAccNum, stUsage, stTTc;
         private static String output=" ";
         private static double usage=0.0;
         private static double TTa=0.0;
         private static double price=0.0;
         private static String lowest;
         public waterBill()
              name=" ";
              accNum=0;
              usage=0.0;
              price=0.0;
         public waterBill(String n,int an, double us, double p)
              setName(n);
              setAccNum(an);
              setUsage(us);
              setPrice(p);
         public void setName(String n)
              name=n;
         public void setAccNum(int an)
              accNum=an;
         public void setUsage(double us)
              usage=us;
         public void setPrice(double p)
              price=p;
         public String getName()
              return name;
         public int getAccNum()
              return accNum;
         public double getUsage()
              return usage;
         public double getPrice()
              return price;
         public double TTaPrice(double price)
              TTa=TTa + price;
              return TTa;
         public String outputInfo(String name, int accNum, double usage, double price )
              String output=" ";                         
              output: System.out.println( "Account Number: "+ accNum +
                                       "\nWater Usage: " + usage +
                                       "\nCost Owing: " price
                                       "\nName: "+ name+"\n");
              return output;
         public void outputoutput(int TTc, double TTa)
              display:     System.out.println("Total customer: "+ TTc +
                                  "\nTotal amount owing: " + TTa + "\n\n");
         public void findGreat()//search the a/c that is greater than 300.
              //dunno how to do, so i just leave it blank^^"
              public String searchDetail()//search the smallest a/c
              //same...dunno how to doT_T     

  • Help populating an array of objects

    New here, trying to figure this out.
    I'm trying to create an array of objects, then populate the array defining fields. I stripped this down as far as i could to simplify the problem but I get the following error when I compile (i tweaked the carrot placment, formating issues i guess):
    PointsTest.java:41: ']' expected
    cubeArray[0] = new Point();
    ^
    PointsTest.java:41: invalid method declaration; return type required
    cubeArray[0] = new Point();
    ^
    2 errors
    My code:
    class PointsTest{
        public static void main(String[] args) {
                   //So far, this works.
                //convert 3 numbers to point coordinates held in temp variables
                float xT = (Float.valueOf(args[0])).floatValue();
                float yT = (Float.valueOf(args[1])).floatValue();
                float zT = (Float.valueOf(args[2])).floatValue();
                Point point1 = new Point(xT, yT, zT);
                point1.printXYZ(); 
    class Point {
        //A BASIC point class
        //fields defined
        float x, y, z;
        //a constructor that sets initial XYZ values
        Point(float startX, float startY, float startZ) {
                x = startX;
                y = startY;
                z = startZ;
        //a no argument constructor for defualt states
        Point () {
            x = 0;
            y = 0;
            z = 0;
        //method
        void printXYZ(){
            System.out.println("coordinates: " + x + " " + y + " " + z);
    class Cube{
         Point cubeArray[] =  new Point[9];
         cubeArray[0] = new Point();
    }I've looked for answers online without much luck, I'm not worried about using a loop to populate the array at the moment (you can do it one at a time, right?). Didn't see any obvious listings in the java tutorials about arrays of objects. Any help would be appreciated.

    You need to put operations inside of a method instead of just floating them around inside the top-level of your Cube class. The errors you are getting are related to the fact that only class data members or methods are supposed to be inside the top-level of a class definition.
    Something like this should get you started:
    class Cube{
            private Point[] cubeArray;
            public Cube(){
             cubeArray =  new Point[9];
    }Regards,
    -MF

  • Trouble creating and populating an array of objects.

    I'm trying to create/populate an array of objects with consisting of a {string, double, integer}, and am having trouble getting this theory to work in Java. Any assistance provided would be greatly appreciated. Following are the two small progs:
    public class HairSalon
    { private String svcDesc; private double price; private int minutes;
    //Create a constructor to initialize data members
    HairSalon( )
    svcDesc = " "; price = 0.00; minutes = 0;
    //Create a constructor to receive data
         HairSalon(String s, double p, int m)
         svcDesc = s; price = p; minutes = m;
    //Create methods to get the data members
    public String getSvcDesc( )
         return svcDesc;
    public double getPrice( )
         return price;
    public int getMinutes( )
         return minutes;
    public class SortSalon
         public static void main(String[ ] args)
         SortSalon [] sal = new SortSalon[6];
    //Construct 6 SortSalon objects
              for (int i = 0; i < sal.length; i++)
              sal[i] = new SortSalon();
    //Add data to the 6 SortSalon objects
         sal[0] = new SortSalon("Cut"; 10.00, 10);
         sal[1] = new SortSalon("Shampoo", 5.00, 5);           sal[2] = new SortSalon("Sytle", 20.00, 20);
         sal[3] = new SortSalon("Manicure", 15.00, 15);
         sal[4] = new SortSalon("Works", 30.00, 30);
         sal[5] = new SortSalon("Blow Dry", 3.00, 3);
    //Display data for the 6 SortSalon Objects
         for (int i = 0; i < 6 ; i++ )
         { System.out.println(sal[i].getSvcDesc( ) + " " + sal.getPrice( ) + " " + sal[i].getMinutes( ));
         System.out.println("End of Report");

    Hey JavaMan5,
    That did do the trick! Thanks for the assistance. I was able to compile and run the program after adding my sorting routine. Do you happen to see anything I can do to clean it up further, or does it look ok? Thanks again,
    Ironjay69
    public class SortSalon
         public static void main(String[ ] args) throws Exception
         HairSalon [] sal = new HairSalon[6];      
         char selection;
    //Add data to the 6 HairSalon objects
         sal[0] = new HairSalon("Cut", 10.00, 10);
         sal[1] = new HairSalon("Shampoo", 5.00, 11);      
         sal[2] = new HairSalon("Sytle", 20.00, 20);
         sal[3] = new HairSalon("Manicure", 15.00, 25);
         sal[4] = new HairSalon("Works", 30.00, 30);
         sal[5] = new HairSalon("Blow Dry", 3.00, 3);
    System.out.println("How would you like to sort the list?");
         System.out.println("A by Price,");
         System.out.println("B by Time,");
         System.out.println("C by Description.");
         System.out.println("Please enter a code A, B or C, and then hit <enter>");
              selection = (char)System.in.read();
    //Bubble Sort the Array by user selection
              switch(selection)
              case 'A':
              BubbleSortPrice(sal, sal.length);
                   break;
                   case 'a':
              BubbleSortPrice(sal, sal.length);
                   break;
                   case 'B':
              BubbleSortTime(sal, sal.length);                    break;
                   case 'b':
              BubbleSortTime(sal, sal.length);
                   break;
                   case 'C':
              BubbleSortService(sal, sal.length);
                   break;
                   case 'c':
              BubbleSortService(sal, sal.length);
                   break;
                   default:
              System.out.println("Invalid Selection, Randomly Sorted List!");
    //Display data for the 6 HairSalon Objects
              for (int i = 0; i < sal.length ; i++ )
         System.out.println(sal.getSvcDesc( ) + " " + sal[i].getPrice( ) + " " + sal[i].getMinutes( ));
              System.out.println("___________");
              System.out.println("End of Report");
    public static void BubbleSortPrice(HairSalon[] array, int len)
    // Sorts the items in an array into ascending order by price
    int a, b;
    HairSalon temp;
    int highSubscript = len - 1;
    for(a = 0; a < highSubscript; ++a)
         for(b= 0; b < highSubscript; ++b)
         if(array.getPrice() > array[b + 1].getPrice())
              temp = array[b];
              array[b] = array [b + 1];
              array[b + 1] = temp;
    public static void BubbleSortTime(HairSalon[] array, int len)
    // Sorts the items in an array into ascending order by time
         int a, b;
         HairSalon temp;
         int highSubscript = len - 1;
         for(a = 0; a < highSubscript; ++a)
              for(b= 0; b < highSubscript; ++b)
         if(array[b].getMinutes() > array[b + 1].getMinutes())
         temp = array[b];
         array[b] = array [b + 1];
         array[b + 1] = temp;
    public static void BubbleSortService(HairSalon[] array, int len)
    // Sorts the items in an array into ascending order by time
         int a, b;
         HairSalon temp;
         int highSubscript = len - 1;
         for(a = 0; a < highSubscript; ++a)
         for(b= 0; b < highSubscript; ++b)
         if(array[b].getSvcDesc().compareTo( array[b + 1].getSvcDesc()) > 0)
                   temp = array[b];
                   array[b] = array [b + 1];
                   array[b + 1] = temp;

  • How to create an array of an object,

    Hi,
    Trying this in Oracle 10.3 studio, I have to use a web service, I have re-catalogued the web service succesfully,
    I am getting compilation error whenI try to create an array of a object,
    Services.PackageTrackingService.PackageTrackingItem[] pkgTrackingItem = new Services.PackageTrackingService.PackageTrackingItem[2];
    I am giving the array size as 2,
    The comilation error is showing as
    Multiple markers at this line
    - statement is expected
    - Expecting ';' but 'pkgTrackingItem' was found
    - expression is expected
    Is there any other way to create the array?
    Thanks in advance.
    -Sree

    Hi,
    Please declare the array in following manner.
    Services.PackageTrackingService.PackageTrackingItem[] pkgTrackingItem;
    Now you can insert the element into the array by pkgTrackingItem[0], pkgTrackingItem[1] etc.
    Bibhu

Maybe you are looking for

  • Memory crashing PC - Doesn't boot

    Hi. I have a MSI865 PE/G Neo2-LS v2 with Bios 3.31a and I'm in some trouble with  oem DDR 400 RAM. I have 2x512 but one chip is 3-3-3-8 and the other is 2.5-3-3-8 Can I use dual channel? I'm asking because each 512 separatelly works but when I use bo

  • Iphoto crashed while trying to share photo to Facebook, can't quit iPhoto or shutdown mac

    please help....???

  • How to hide the owner name on the client

    Hello, I would like to ask is there any possibility to hide the owner and description details while selecting the report on the client end i.e. Discoverer viewer. My client has issues in the owner name being displayed over there... Thanks!

  • Conditional Not Null

    I am trying to create an item level validation on an entry form for a Conditional Not Null. For example ... Field 1 = Animal Type Field 2 = Dog Type If Field 1 = Dog .... Field 2 must be Not Null. Can someone help me set this up. Thanks in advance fo

  • Strange phone setup in new build

    Just moved into a brand new house and while trying to improve my (dreadful) broadband speed came across what I think might be incorrect wiring of the telephone system. My setup is as follows: The BT drop wire comes out from undergound in a grey BT br