Results 1 to 14 of 14
  1. #1
    thedarlington is offline Member
    Join Date
    Feb 2010
    Posts
    6
    Rep Power
    0

    Default creating objects by methods automatically

    hi everyone newbie here so glad to find this forum, this is my 1st thread, im trying to make a program that

    1 reads info from a txt, parses and
    2 creates a new object from the info provided and a class 'blueprint' im supposed to create, the objects would be created through methods,
    3, store objects in an array automatically,

    so it would be something like this



    create array with specified size

    for(int i=0, i<arraylenght, i++)
    {
    start scanning txt,
    create course object using data of first line and class template <<<== how? and how would it know how to name each object? i only need a simple name like c1 c2 etc, could i code something like 'c'+[i] ?

    store to array @ array[i]

    }


    they are school courses, and are supposed to be one course per object, with fields like name, # students, teacher etc, as the program reads the file, its going to populate that course object's fields with the values specific to it, for example, intro101, math intro, smith, 20 etc, using a for loop

    my problem is that the code ive got, which is incomplete, is full of error and i dont really know how to interpret it, because while i understand the theory ok, i aint no code ninja, so i just get overwhelmed and get stuck, i got my scanner fairly well, but what i dont know how to work is step 2, making a new object through a method, and letting it be populated with a for loop automatically, i also expect i need to pass values in the header, but i dont know how exactly it goes, like i said, i kind of know what im talking about, but when it comes to coding it i just cant, can anybody help me out?


    Java Code:
    import java.util.Scanner;
    import java.io.*;
    
    
    public class Courses
    {
                               
    /**
                                *The 1st String t = readLine() will read the 10
                                *
                                *create array using # specified in txt
                                *for loop here
                                *get txt courses info with scanner
                                *create couse object;
                                *store object to array at array[i]
    	                    */
    
    
        public static void main(String[] args) {
        //run individual methods
            makearray();
            makeclassobj();
    //ERROR_ABOVE, errors on both lines above, my method call isnt correct
    
        }
    
    //	public void makearray(String[] args)throws IOException
            //1 READSTUFF to read n create array size
    	{
    		String      fileName    =   "coursestuff.txt";
    		String      input       ;   //input from readline
    		Scanner     sc          =   new Scanner("coursestuff.txt"); //new Scanner(new file(""))
                    int         totalcr     ;
    
                    input       = scanner.readLine();       
    //ERROR_ABOVE, cannot find symbol? dont know what that means
    
                    totalcr     = Integer.parseInt(input); 
    
    
                     //BUFFER READER WAY -NOT USED-   FileReader freader = new FileReader(fileName);
                     //BufferedReader inputFile = new BufferedReader(freader); input = inputFile.readLine();
    
    
                    totalcr = Integer.parseInt(input);
                    CrAy[] = new CrAy[totalcr] ;
    //ERROR_ABOVE, 'not a statement, ; expected'
    
            }       //read 1st line and parse to int   4-12 codeline 27
    
    //        public void makeobjclass(crblueprint)
            {
                
                private C[i];
    //ERROR_ABOVE, illegal start of expression and ] expected
    
                    for(int i=0 ;   i>CrAy  ;   i++)
    //ERROR_ABOVE, illegal start of type, cannot find symbol CrAy, identifier expected
                    {
                        crblueprint
                        CrAy[i] = c[i];
    //ERROR_ABOVE,  ] extected, ; expected
    
                    }
    
            }
    
            public void populatearray()
    //ERROR_ABOVE, class, interface, or enum expected
            {
                        private CrAy[]
                        line        = Scanner.ReadLine()
                        Scanner sc  = new Scan(line);
    
    //ERRORS ALL 5
                        crn         = sc.nextInt();
                        title       = sc.ntxt();
                        id          = sc.next();
                        capacity    = sc.nextInt();
                        current     = sc.nextInt();
    //ERROR_ABOVE, class interface or enum expected
    
            }
    
    
    
    
    
    
    
    
    
    		//3 store to array
    
    
    
    
    
    /**		public static void readstuff {
    *			String x	= newScanner("textcourses.txt");
    *			int toc		= Integer.parseInt(x);
    *			array		= newCourse[toc];
    *
    *			line =		Scanner.readline()
    *			Scanner s2	= newScan(line);
    *			crn			= nextInt();
    			title		= s2.next();
    			id			= s2.next();
    			capacity	= s2.nextInt();
    			current		= s2.nextInt();
    
    *		//for loop here
    *		course c1		= newCourse
    *		array[0]		= c1
    */
    
    		}
    
    }
    Last edited by thedarlington; 02-05-2010 at 11:42 PM.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Welcome to the forum!

    Why don't you post your code (with code tags -- please see my signature below), post the errors you're getting, indicate in your code with comments which lines correspond to the lines in the error messages, and I'll bet we can help sort things out some.

    Much luck!

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by thedarlington View Post
    so it would be something like this
    Java Code:
    create array with specified size
    
    for(int i=0, i<arraylenght, i++)
    {
    start scanning txt,
    create course object using data of first line and class template   <<<== how? and how would it know how to name each object? i only need a simple name like c1 c2 etc, could i code something like 'c'+[i] ?
    
    store to array @ array[i]
    
    }
    Objects don't have names, variables do, and here the important variable with the name is the array. You'll create your object and place it into your array at index [i].

  4. #4
    thedarlington is offline Member
    Join Date
    Feb 2010
    Posts
    6
    Rep Power
    0

    Default

    thanks for the tip, i hope those errors i wrote make sense, thank you for your quick reply, so if the names dont matter for objects, how would someone know what object was just created? would this be the line then, if course is my master class template

    Course c1 = new Course() or Course c1 = new Course(title, students, teacher, etc)
    Last edited by thedarlington; 02-05-2010 at 11:50 PM.

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Yikes.
    You need to start over, I think but use a different technique for creating your code. Right now you're typing in the code and then when you're done, compiling the whole shebang which is not the right way to do this as you're getting compounding errors. Instead what you need to do is add one to two lines at a time, and then after adding these 1-2 lines, compile the code right away. Then if you find any errors, don't add any more code until the errors have been corrected. Otherwise you'll end up with a rat's nest of errors that are uncorrectable.

    So again, you're best off trying again.

  6. #6
    thedarlington is offline Member
    Join Date
    Feb 2010
    Posts
    6
    Rep Power
    0

    Default

    ok well i could just try testing out each part in a new main, but is there any program out there that would help me to umm debug my code? i dont really get why i get some errors, like those where ive already got the [ or ; and it still asks for them

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by thedarlington View Post
    ok well i could just try testing out each part in a new main, but is there any program out there that would help me to umm debug my code? i dont really get why i get some errors, like those where ive already got the [ or ; and it still asks for them
    You're getting errors because of many reasons including calling methods that don't exist, using variables that have not been declared, having method bodies but commenting out the top line of the method (its signature), ... and that only touches the surface of it.

    Most of us use an IDE such as NetBeans or Eclipse for creating programs as they help us by flagging errors as we type in lines, but since the IDE's are complex, many advise newbies to avoid this at first so you don't have two learning curves to worry about -- Java and the IDE.

  8. #8
    thedarlington is offline Member
    Join Date
    Feb 2010
    Posts
    6
    Rep Power
    0

    Default

    ok so i got a question, whats wrong with my first 2 method calls? what am i missing? and am i suppose to pass something in the ()?
    the method is supposed to simply read the first line of txt, a #, int parse, and create an array with it,
    thats where i get to my big issue, since im using scanner throughout, is it right to put that code in that method? should i have a method that just takes care of scanning, and waits for each time its needed to scan the next line? the problem is, i could do it if it where all in the main, but by methods its kind of confusing

  9. #9
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by thedarlington View Post
    ok so i got a question, whats wrong with my first 2 method calls? what am i missing? and am i suppose to pass something in the ()?
    Take this code:
    Java Code:
    public class Courses {
    
       public static void main(String[] args) {
          makearray();
          makeclassobj();
       }
       
    }
    You're calling two methods here, makearray and makeclassobj that don't exist anywhere in your code, and so the compiler is complaining about this, and preventing the java code from compiling into a class file. To fix this, you need to give your class the methods above like so:

    Java Code:
    public class Courses {
    
       public static void main(String[] args) {
          // run individual methods
          makearray();
          makeclassobj();
       }
    
       public static void makeclassobj() {
          // code goes in here
       }
    
       public static void makearray() {
          // ditto
       }
       
    }


    I also notice that your code already has the first method, makearray, but its signature, its first line has been commented out:
    Java Code:
    //	public void makearray(String[] args)throws IOException
    If you want to create and use a makearray method similar to this one above, then yes, you'll have to pass parameters into the method when you call it that match the parameters declared in the method signature above: an array of String. Fortunately if you look at your main method's signature:
    Java Code:
    public static void main(String[] args) {
    you'll see that it also just happens to have such an array as the argument in its parameter and it's been given the same name, args (which isn't necessary). So to use a method with a String array parameter, you'll need to do something like this:

    Java Code:
    public class Courses {
    
       public static void main(String[] args) throws IOException {  // you'll need a throws IOException here too
          // run individual methods
          makearray(args); // here we pass the args parameter into the makearray method
          makeclassobj();
       }
    
       public void makearray(String[] args)throws IOException {
          // code goes in here
       }
    
       public static void makearray() {
          // ditto
       }
       
    }

    the method is supposed to simply read the first line of txt, a #, int parse, and create an array with it,
    thats where i get to my big issue, since im using scanner throughout, is it right to put that code in that method? should i have a method that just takes care of scanning, and waits for each time its needed to scan the next line? the problem is, i could do it if it where all in the main, but by methods its kind of confusing
    I'm guessing that the line of text is coming from your command line parameters, but it's just a guess. You may want to post the actual assignment here along with any code that has been given to you (before you've made changes to it).

  10. #10
    m00nchile is offline Senior Member
    Join Date
    Feb 2010
    Location
    Ljubljana, Slovenia
    Posts
    470
    Rep Power
    5

    Default

    Storing objects into an array is acctually the same as storing ints, so, for your example:
    Java Code:
    MyObject[] objarray = new MyObject[n]; //assume n is already given
    for(int i = 0; i < n; i++) {
         //get the info you need to make your object
         objarray[i] = new MyObject(arg1, arg2...);
    }
    And that is the gist of your problem, from what I can tell. A more clear example might be something more fammiliar, like Integer objects:

    Java Code:
    Integer[] array = new Integer[10];
    for(int i = 0; i < 10; i++)
         array[i] = new Integer(i);
    And the result would be an array with Integer objects from 0 to 9. Creation of objects and storing them in the array can be accomplished in the same line. Of course, you could get the same result with:
    Java Code:
    Integer k;
    Integer[] array = new Integer[10];
    for(int i = 0; i < 10; i++) {
           k = new Integer(i);
           array[i] = k;
    }

  11. #11
    thedarlington is offline Member
    Join Date
    Feb 2010
    Posts
    6
    Rep Power
    0

    Default

    hey everyone thanks for all the quick help, you guys really helped alot, i took the advice and rewrote most of it, now i don''t have half as many errors, i think the problem for me is that once i visualize it i need to put it down in code, otherwise ill just get confused, it helped alot to write the pseudocode on paper first,

    sorry for not being able to write back yesterday, when i shutdown my computer that night it didnt take too well to whatever the hell update microsoft sent (doesnt like you upgrading ur hardware) and ive still got xp, i could only imagine the nightmare all the locks vista and 7 must have, id love to just get on linux but unfortunately i got some programs that keep me locked in, cs4 and some music making stuff

    anyway well im back in business this is what i got now...

    Java Code:
    import java.util.*;
    import java.io.*;
    
    /*
    
     */
    
    public class SANDBOX {
    
    public static void main(String[] args) throws IOException
    {
        scanmeth();
        makearray();
        makeobjmeth();
        populatemeth();
    }
    
    
    public static String scanmeth() throws IOException
        {   String      fileName    =   "coursestuff.txt";
            File        file        =   new File("coursestuff.txt");
    	Scanner     sc          =   new Scanner("file"); //new Scanner(new file(""))
            String      input       =   "";
    
            FileReader freader = new FileReader(fileName);
            BufferedReader in7 = new BufferedReader(freader);
            input = in7.readLine();
            return input;
        }
    
    
    public static CrAy[] makearray(String input)
        {   int         totalcr     =   0;
            
            totalcr     = Integer.parseInt(input)  ;
            CrAy[]      = new Crblueprint[totalcr] ;
            return CrAy[];
        }
    
    public static void makeobjmeth()
        {   for(int i = 0 ; i < CrAy.length ; i++)
            CrAy[i]     = new Crblueprint();
    }
    
    public static void populatemeth()
        {   for(int i=0 ; i < CrAy.length ; i++)
    
    
    
    }
    
    
    }
    i got errors pretty much every line u see CrAy, thats my array, and im still not quite clear on the creating objects by loop, you guys had already said how to create them normally, but for the program to dinamically make them? is it even possible?
    Last edited by thedarlington; 02-07-2010 at 08:14 PM.

  12. #12
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Sorry, but you've lost me here as I'm not sure what you're trying to do. Do you have code for a CrAy class somewhere? The code above assumes that you do. The code still seems still a bit disjointed, almost a "stream of consciousness" type of coding, but unfortunately while poetic license is great for writing literature, this doesn't work in programming.

    What you still need to do is to break your problem down into its smaller constituent parts, and then solve each part, perhaps each method, one at a time, not moving onto the next method until the one you're working on is fixed.

  13. #13
    thedarlington is offline Member
    Join Date
    Feb 2010
    Posts
    6
    Rep Power
    0

    Default

    wow i thought it was pretty broken up already, sorry the CrAy is my course array name, the makearray() method is supposed to create the array and pass it (return it), ok can u think of anything that looks wrong on the makearraymethod then? thats really where im getting all the errors, it highlights the CrAy[] i have in its header, the return line, and the CrAy in the line above it, did i not define it right or something?

  14. #14
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    I think one basic misunderstanding that you're having is you're mixing up class declarations with variable names.

    For example this:
    Java Code:
    public static CrAy[] makearray(String input)
    {
       //...

    means that the makearray method will return an array of CrAy, whatever that is. If instead it is supposed to return an array of Course objects (assuming that you have a Course class code somewhere), then you need to instead do this:
    Java Code:
    public static Course[] makearray(String input)
    {
       //...

    Based on this statement of yours:
    they are school courses, and are supposed to be one course per object, with fields like name, # students, teacher etc, as the program reads the file, its going to populate that course object's fields with the values specific to it, for example, intro101, math intro, smith, 20 etc, using a for loop
    it looks like you are either given this class or need to make it.

    This statement here:
    Java Code:
    CrAy[]      = new Crblueprint[totalcr] ;
    doesn't make sense as it looks like you're declaring an array of CrAy objects but don't give it a name. Then you set it equal to an array of Crblueprint objects whatever they are. It's as if you're making this stuff up.

Similar Threads

  1. Creating an Array of Objects
    By int80 in forum New To Java
    Replies: 4
    Last Post: 08-09-2011, 12:40 PM
  2. Creating custom objects
    By coltragon in forum New To Java
    Replies: 11
    Last Post: 12-29-2009, 10:50 PM
  3. Creating Array of Objects
    By chathurajeewaka in forum New To Java
    Replies: 4
    Last Post: 12-03-2009, 03:23 PM
  4. Creating an array of objects
    By geowizard in forum New To Java
    Replies: 5
    Last Post: 11-16-2009, 01:25 AM
  5. Creating objects question
    By sergm in forum New To Java
    Replies: 2
    Last Post: 12-27-2007, 04:10 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
  •