Passing a string as an object name...how?

I've searched all over the place for a solution to this to no avail.
I have a program that reads input from a text file. The text file holds information on student IDs, so it look something like this:
"ID_1234"
"ID_1235"
"ID_1236"
So, every line of the text file has a student ID.
I have a class called Student, that takes the student ID as a parameter, so I can create a Student object pretty easily by going, for example:
Student newStudent = new Student("ID_1234");
Now, my problem is that I want to read the contents of the text file that is given to me and create an object for each student, and use as a name for that object the student's ID. I have the program reading the data from the text file no problem, it's just the object name assignment I'm having trouble with.
//Start code
private void readInStudents(String fileName){
BufferedReader reader = new BufferedReader (new FileReader (studentIDFile.txt));
String line = reader.readLine();
while(line != null)
Student line = new Student(line);
//End code
Ideally I would like this to crate three Student objects, with the names "ID_1234", "ID_1235", and "ID_1236" respectively.
However, this is not the case as I get an error when assigning "line" as the object name in the line within the while loop.
Any help would be much appreciated!!!!!!
Many thanks.

elsombreron wrote:
Thanks to all for your quick replies. I ended up using an ArraList to store the objects without needing to give them all a dynamic name.
I come from a purely procedural programming background where the sort of assignment I was trying to do would work, so still have to get used to OO style.
Thanks again.Huh? I don't see what procedural vs object oriented has to do with it.
FORTRAN, COBOL, C and Ada (pre 95) are all procedural languages and as far as I can remember, you could not do that in any of them.
Perhaps many scripting languages allow this. The various *nix shells come to mind.
What languages are you referring to that have tis feature?

Similar Messages

  • Is it possible to pass a string representing a class name in java as an arg

    Hi, this is probably a bit of a stupid question, but one that has me quite confused all the same!
    Is it possible to pass a string or class name etc. representing a type of class in java, to a method so that instead of having to redefine a method with say the following args:
    public SolarPanels[] bestPVPanels(int budget, int percent) {
            HashMap<Integer, SolarPanels> panelsMap    = new HashMap<Integer, SolarPanels>();
    }As at present needing to create a methods bestWindTurbine() and many others exactly the same, but for the type, I would instead like to be able to create a method like:
    public Object[] bestRenewable(int budget, int percent, String aClassName) {
            HashMap<Integer, aClassName > renewableMap    = new HashMap<Integer, aClassName >();
    }But cant sus how to do this as passing a String is off course going to cause problems unless its it possible to cast a string to a class name, any help or advance would be much appreciated.
    Thanks in advance
    Pat Nevin

    pNev wrote:
    But cant sus how to do this as passing a String is off course going to cause problems unless its it possible to cast a string to a class nameIt's not. You can do things like
    Class.forName(classNameInString);But that will only return a Class object.
    And as Java generics are erased at runtime, passing the class name to the method is useless as it is too late to use it anyways.
    Ah, Peter's way is what I was thinking of. Too early in the morning.
    Edited by: Kayaman on 23.6.2010 10:02

  • How to convert a string into an objects name?

    Hi
    I have the following problem;
    I have a string
    String a = "e1"
    and a method
    call(Event e1) that calls the "Event" class with object the name of the string a.
    How can I convert the strings name into an object so as to use it in the "call" method?
    Any ideas?
    Thanks in advance

    I don't know if this helps you, but you can do things like this.
    String a = "com.example.SomeEvent";
    //Instantiate com.example.SomeEvent
    Object o = Class.forName(a).newInstance();SomeEvent must have a non-argument constructor for this to work.
    Class that will be instantiated depens on runtime value of String a, and can be different across different executions of the program.

  • How to Pass a String as a MovieClip Name?

    Hi everyone! I'm back with more doubts
    I created 4  buttons with 4 animations each, one for each state (using tweens), so I  have that imense list of 16 "addEventListeners" (don't know if there's  another way to do it). But everything is working as I would like.
    The  problem is that I'm trying to create only 4 functions to take care of  all the 4 buttons and those 16 eventListeners.
    This is  part of my AS3 file (still with the "traces", 5 secs of animation to  check the animations and all).
    empresa_btn.addEventListener(MouseEvent.MOUSE_OVER, isOver);
    empresa_btn.addEventListener(MouseEvent.MOUSE_OUT, isOut);
    empresa_btn.addEventListener(MouseEvent.MOUSE_DOWN, isDown);
    empresa_btn.addEventListener(MouseEvent.MOUSE_UP, isUp);
    parceiros_btn.addEventListener(MouseEvent.MOUSE_OVER, isOver);
    parceiros_btn.addEventListener(MouseEvent.MOUSE_OUT, isOut);
    parceiros_btn.addEventListener(MouseEvent.MOUSE_DOWN, isDown);
    parceiros_btn.addEventListener(MouseEvent.MOUSE_UP, isUp);
    var mouseState:String;
    var mouseActive:String;
    var txt:String;
    empresa_btn.over.alpha = 0; empresa_btn.down.alpha = 0;
    parceiros_btn.over.alpha = 0; parceiros_btn.down.alpha = 0;
    function isOver (e:MouseEvent):void {
         mouseActive = e.currentTarget.name;
         mouseState = "isOver";
         trace (mouseActive + " " + mouseState);
         var isOver:Tween = new Tween(empresa_btn.over, "alpha", Strong.easeOut, empresa_btn.over.alpha, 1, 5, true);
    function isOut (e:MouseEvent):void {
         mouseActive = e.currentTarget.name;
         mouseState = "isOut";
         trace (mouseActive + " " + mouseState);
         var isOut:Tween = new Tween(empresa_btn.over, "alpha", Strong.easeOut, empresa_btn.over.alpha, 0, 5, true);
    Now, what I'm trying to do is use the var "mouseActive"  that is returning the right button names inside the Tween as the  movieClips.
    The problem is that "e.currentTarget.name" is not the  "movieClip" itself... it's just a String with the name of the movieClip.
    Example:  whenever I try to do something like this:
    var isOut:Tween = new Tween(mouseActive.over, "alpha", Strong.easeOut, mouseActive.over.alpha, 0, 5, true);
    It will return an error cause, as I said, mouseActive is not a  movieClip, it's just a String (at least I think).
    I already  thank you for the help (again)
    And please, mind my nickname

    Ned Murphy wrote:
    You're welcome.
    As a further opportunity to reduce code, since all your listeners are identical...
    var btnArray:Array = new Array(btnNames go here, no quotes);
    for(var i:uint=0; i<btnArray.length; i++){
         btnArray[i].addEventListener(...OVER...);
         btnArray[i].addEventListener(...OUT...);
         etc... including where you set alpha = 0
    Gosh Ned! I had about 25 big lines of code, including things like "buttonMode = true" and now I have less than 10
    This is totally crazy! I always tried to understand this array thing and always failed. It's complicated but your code made some sense after a while
    I'm running out of "thanks" to give you hehe. Everything is working just fine but one little thing. I have a sound that plays when a button is clicked. It's working fine but everytime I open the swf the sound autoplay once =/
    I'm using this code:
    var btnSound:Sound = new clickSound(); //"clickSound" is the className I choosed when exported the sound to AS from the library
    and then, inside the function MOUSE_DOWN I have:
    btnSound.play();
    Everything is working but I always hear the button sound playing one time when I open the swf. Do you know why?
    Well, you already helped me a lot. Even more that I could have asked for.
    Thanks!

  • Passing a string as the name of a Mouse Event Listener function?

    Hello,
    I am trying to essentially pass a string as a function name into an event listener, but I am not sure how to approach this.  Is there a way to convert a string into a function?  I am not sure how to word my question, so I apologize.
    Here is some code I have for me to show you what I am doing.
    package{
         //some import statements
         public class changes extends MovieClip{
              var functionName:String
              var aBox:Sprite;
              public function changes(){
                       functionName = "testThis";
                       createButtonBox(16, 16, 32, 32,  functionName);
              public function createButtonBox(anX:Number, aY:Number, aWidth:Number, aHeight:Number, aFunction:String){
                   aBox = new Sprite();
                   //Some drawing box code
                   aBox.addEventListener(MouseEvent.CLICK,[aFunction]()?)
                   addChild(aBox)
              public function aFunction(event:MouseEvent){
                   trace("test");
    Am I on the right track or is this not possible?
    Anyhow, thank you in advance.

    I guess I misworded my question.  Essentially what I am trying to do is create buttons that have functions called to from an event listener, referenced by a string like this:
    public class Document{
         var functionName:String;
         public function Document(){
                 createAButton("Test Button A", 32, 32, "testThis");
                 createAButton("Test Button B", 64, 64, "testThis2");
         public function createAButton(textOnButton:String, anX:Number, aY:Number, functionToCallTo:String){
                   var aButton:Sprite = new Sprite();
                   //draw the button
                   //set a textfieldup for the button to have
                  aButton.addEventListener(MouseEvent.CLICK, functionToCallTo)
         public function testThis(event:MouseEvent){
                   trace("testA");
         public function testThis2(event:MouseEvent){
                    trace("testB");
    Unfortunately aButton.addEventListener(MouseEvent.CLICK, functionToCallTo) gives me a coercian error, which is a given.
    aButton.addEventListener(MouseEvent.CLICK, [functionToCallTo]()) gives me TypeError: Error #1006: value is not a function.
    I mean I could create a bunch of if statements, but for the number of functions I plan to call to, like about 25 or so, that is pretty tedious.

  • Making an object name

    Hi All,
    I have to do what I thought was a simple thing:
    A cue point comes into my function and is read. I find the name of that cue point (which is the name of the MC it will act upon) and convert it from a string to an object name so I can work on it. Here's how I do that:
    function onCuePoint(event:CuePointEvent):void
      trace (event.name);                                                       // output: "childMovieClipA" <==this is a string.
      newChildObjectName = this[event.name];
      trace ( newChildObjectName.name );                          // output: "childMovieClipA" <==this is an object..
    That works. How do I make the name of another related MC by adding a string to the event.name and then convert that string to an object name?
    I'm trying to create the name of this MC: "childMovieClipA_grandChild"
    For example, I'm trying to do this below but get an error:
      newGrandChildObjectName = this [event.name + "__grandChild"];
      trace ( newGrandChildObjectName.name );                //TypeError: Error #1010: A term is undefined and has no properties.
    Any help is appreciated.

    In your example it appears you use two underscore characters whereas what you say you want to create appears to only have one.
    The way you say you want it places it at the same child level as the event.name object.  Just in case, if the _grandchild is a child of the event.name object, you need to use a separate pair of brackets for it.

  • How to pass a String and make it as Color Object

    I need to set a background color dynamically...but the value that i pass is in string format. How can i convert the string into Color format so that i can use the method setBackground(Color.blue) method. How to pass the string into the 'Color.blue' ?

    Let param="red"
    Class cls = Class.forName("java.awt.Color");
    java.lang.reflect.Field fld = cls.getDeclaredField(param);
    Color clr = (Color)fld.get(null);
    You can use this 'clr' variable as you wish.
    null

  • How to pass a string value from XL sheet cell to SQL query.

    Hi,
    I am using SQL query in XL sheet to fetch some data. for that i am using ODBC connection. Now I want to pass a string from XL sheet Cell value in the where clause of Select statement, Please let me know how to do this.
    Below is My code:
    nge("A4").Select
    With ActiveSheet.QueryTables.Add(Connection:= _
    "ODBC;DRIVER={Microsoft ODBC for Oracle};UID=xyz;PWD=xyz;SERVER=xyz;" _
    , Destination:=Range("A4"))
    .CommandText = Array( _
    "SELECT CRYSTAL_REPORT1.PROJECT, CRYSTAL_REPORT1.OBJECT" & Chr(13) & "" & Chr(10) & "FROM NAIODEV.CRYSTAL_REPORT1 CRYSTAL_REPORT1" _
    .Name = "Query from gg"
    Thanks,
    Priya

    What does "XL" (whatever that is) have to do with Crystal Reports which is what you are obviously working with have to do with the Oracle database?
    The rules for using Crystal with Oracle are quite clearly described in all the Crystal Reports docs ... you MUST use IN OUT ref cursors unless you are doing direct table or view access.

  • How can I pass a String by reference in java?

    Hello!
    My question is how to pass a String by reference in java.
    I tried to declare my variable, instead of using "String xxx = "f";", I used "String xxx = new String ("f");" :
    public static void main (String []args)
    String xxx = new String("f");
    StatusEnum result2 = getErrorPointStr(xxx);
         public StatusEnum getErrorPointStr(String text)
              StatusEnum testStatus = StatusEnum.PASS;
              StringBuffer buffer = new StringBuffer();
    buffer.append("123");
              text = buffer.toString();
              return testStatus;
    After calling to getErrorPointStr(String text) function, xxx = "f"
    So it does not work.
    How can I solve this? It is very important, the function will receive String and not something else.
    Thanks!

    Tolls wrote:
    Which is why I said:
    Which is why you only managed to change what 'text' referred to in the methodExcept that's not why. Even if String was mutable, doing text = whatever; would have the same effect; it would change what that variable refers to in the method, but it would not change the object's state.
    I meant that, since there was no way to actually change the data (ie the char[] or whatever) within the object 'text' referred to, the OP was attempting to change what 'text' referred to and hoping it would be reflected outside the method...which we know won't happen as Java is pass-by-value.\Ah, now I see.
    These by-value/by-reference threads tend to get confusing, because usually the person is passing a String, so the immutability of String tends to get in the way and just muddy the waters.

  • String in object name

    hi, wondering if someone can help me,
    i have some script in which the object name will be created
    from a string and now i need to call another object within the
    object and not sure how to do it.. here is some code:
    u will see on the first line of the code an object is
    duplicated with a new name
    and on the last line i need to change the value of an object
    within that new object i duplicated.. no i am not show how to do it
    with it's new object name, at the moment i just tried pic+i
    u see on the 2nd line i am able to do it because i am able to
    put the object path within " ".
    hope it not to confusing.

    Accessing pic+i+.button will act as variable. You need to
    Evaluate this using either a Square Bracket or evaluate function,
    See the below Code using the " [ ] " for evaluation

  • How to add an variable to the object name of the arraylist

    Greetings,
    i will like to create an object for arraylist with it name concat with a variable. This is what i mean as show below.
    for i=1; i <8; i++)
    ArrayList list = new ArrayList();
    What i want when it loops, the arrayliost will auto create list1, list 2, list3 and so on until the for loops end. How do i add the variable i to the object name list?
    Thanks

    Do anyone of u mind if let me know hows the code look like?This isn't intended to be an alternative to the previous reply: in fact it's worthless unless you read the information in the link given.
    import java.util.ArrayList;
    import java.util.InputMismatchException;
    import java.util.List;
    import java.util.Random;
    import java.util.Scanner;
    public class ListListEg {
        public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            Random random = new Random();
                // create the mainList outside the for loop
            List<List<Integer>> mainList = new ArrayList<List<Integer>>();
            System.out.print("How many lists would you like? ");
            try {
                int num = in.nextInt();
                if(num <= 0) {
                    System.out.println("Smartass!");
                    System.exit(1);
                    // populate the main list inside the loop
                for(int i = 0; i < num; i++) {
                    mainList.add(new ArrayList<Integer>());
            } catch(InputMismatchException ime) {
                System.out.println("Idiot!");
                System.exit(1);
                // later do stuff with the lists, which you access with get()
            for(int i = 0; i < mainList.size(); i++) {
                for(int times = 0; times < 3; times++) {
                    mainList.get(i).add(random.nextInt());
            System.out.println("The first list is " + mainList.get(0));
            if(mainList.size() > 1) {
                System.out.println("The second list is " + mainList.get(1));
            System.out.println("The last list is " + mainList.get(mainList.size() - 1));
    }(In reality all the action would not take place in one method like this, and the exception handling would be more useful and polite.)

  • How to code a method that returns string for class object

    I have a class named Address.
    public class Addresss{   
    private String street;   
    private String city;            // instance variables  
    private String zipcode;}I have been asked to write a method that returns a string for Address object. I dont understand how to create address object.Can anyone pls help me understand.
    do I have to write (for creating object)
    Address addressObject  = new Address(); ( coding method that returns a string for address object) ---> I really dont understand this part.

    looks almost right. The problem is that your method name AddressBookEntry does not match the name of your class AddressBook and therefore is not a constructor.
    Furthermore, you probably need to make a distinction between a single entry into the address book which consists of a single name and a single address, (which is just what you have done) and an address book itself which is probably a list of AddressBookEntries
    So for your code I would change the class that you called "AddressBook" to "AddressBookEntry" and have a third class that represents the collection of AddressBookEntries.
    Now to be honest, I don't know why you keep the name split apart from the street address portion of the address. I would be more inclined to keep the name as a field of the address itself, but it's your code, you carve it up the way you like.

  • How can I pass a String to a mxml?

    I am trying to pass a string to mxml file.
    following are the part of codes:
    var renderPDFForm:RenderPDFForm=new RenderPDFForm();
    mx.core.Container.addChild.addChild(renderPDFForm);
    The RenderPDFForm is actually a mxml file, I want to do something like when creating the instance, a string can be called.
    Since we can't create constructor for mxml file, how I can do it?
    Thanks,

    So within your mxml file for the RenderPDFForm component:
    <mx:Script>
        <![CDATA[
            private var _myData:String;
            public function set myData(str:String):void{
                _myData = str;
          public function get myData():String{
                return _myData;
        ]]>
    </mx:Script>
    Then in your main app:
    <comp:RenderPDFForm myData="My nice string"/>
    where comp is your namespace name.

  • Passing a String object from Application.start() into a Controller

    This is probably really obvious to most reading this question, but I'm perplexed on something.
    I'm working on a JavaFX application that is embedded on a web page and I've specified a couple of values in the "params" of the dtjava.embed() function. I can access those values through the Application.getParameters() call in start(). Great.
    The challenge now is that I'm starting to use an FXML file and I want to pass the String values to the Controller that is managing the FXML page.
    The closest I think I've come so far is to possibly use:
    FXMLLoader fxmlLoader = new FXMLLoader();
    URL location = getClass().getResource("Sample.fxml");
    fxmlLoader.getNamespace().put("UserId", UserId);
    fxmlLoader.getNamespace().put("OrgId", OrgId);
    Parent root = (Parent) fxmlLoader.load(location.openStream());Even with this, I'm not sure how to access the values inside the controller object.
    Any suggestions would be greatly appreciated.
    ~~ Michael
    Edited by: Michael_M on Jan 24, 2012 12:22 PM
    Edited by: Michael_M on Jan 24, 2012 12:22 PM
    Edited by: Michael_M on Jan 24, 2012 12:22 PM

    I solved it by getting the controller from the loader after loading the FXML and then provide the controller with the relevant data.
    You can get the controller if you don't use the static load methods. In case anyone else has this question, here's what I did:
    FXMLLoader fxmlLoader = new FXMLLoader();
    URL location = getClass().getResource("Sample.fxml");
    fxmlLoader.getNamespace().put("UserId", UserId);
    fxmlLoader.getNamespace().put("OrgId", OrgId);
    Parent root = (Parent) fxmlLoader.load(location.openStream());
    Sample s = (Sample) fxmlLoader.getController();
    s.UserId = UserId;
    s.OrgId = OrgId;

  • How can I set the Object Name to the file name on import?

    All-
    I've been manually typing the filename into Aperture's Object Name metadata field. Is there a way to do this automatically? I use metadata presets to fill in many other fields on import but haven't found a way to set metadata fields on a file-by-file basis.
    Perhaps there's a way to do this with the thousands of images already in my library as well...
    Thanks,
    Andreas

    Here's the cleaned-up version:
    tell application "Aperture"
    set selectedImages to the selection
    repeat with i in selectedImages
    set tName to name of i
    set value of IPTC tag "ObjectName" of i to tName
    end repeat
    end tell
    Some other related bits, which you can probably work out how to put into the above script:
    Find out the AppleScript names of the IPTC tags (but only tags which have a value for that image), the names will be listed in the 'result' pane in the Script Editor:
    tell application "Aperture"
    set selectedImages to the selection
    get name of every IPTC tag of item 1 of selectedImages
    end tell
    The same for EXIF tags:
    tell application "Aperture"
    set selectedImages to the selection
    get name of every EXIF tag of item 1 of selectedImages
    end tell
    And for any custom tags you have set up. If you haven't set up any custom tags (one of my main reasons for going with Aperture) this will just return camera and picture time zones:
    tell application "Aperture"
    set selectedImages to the selection
    get name of every custom tag of item 1 of selectedImages
    end tell
    Finally, keywords:
    tell application "Aperture"
    set selectedImages to the selection
    get name of keywords of item 1 of selectedImages
    end tell
    To grab the first keyword name try 'name of keyword 1 of...' etc.
    To grab the parent keywords for hierarchical keywording stuff try experimenting with 'get parents of keywords of'. The keywords seem to be read-only from AppleScript, so a magic script that added all parent keywords doesn't seem to be possible.
    Ian

Maybe you are looking for

  • Update "error" message

    When trying to update my iPod the error message "The ipod cannot be updated because one or more of the iTunes playlists selected to be updated no longer exists" appears. Not sure what this means... any help circumventing this error message would be m

  • Problems 'hosting out' of java

    Hi, JDeveloper version 9.0.3.1035 Windows NT I am having problems 'hosting out' of java. The dos command shell is opened but little else happens. I am trying to run a batch file called test.bat that has contents: - notepad.exe My code is : - public s

  • A bug in the interaction between webkit popups and AIR

    Hi all, I came across this thread in the archives, dealing with an HTML select box that did not work properly in an AIR utility window. Since I just finished a mini ordeal around the same problem, I'd like to share: When you activate an HTML popup (e

  • EHS - Synchronization error when trying to generate WWI accident report

    Dear all, I have a problem with WWI accident reports. I have created an accident report template (from the example SOP template), released the template and assigned a generation variant to it. When I try to generate the accident report from CBIH82 Ed

  • Problem about duplicate use

    Hi,All I have used je with dbConfig.setSortedDuplicates(true); Then I stored my data just using db.put(key, value); The problem is that data bloated seriously.My key of every record is int,and the value is about 100 bytes.I have put about 3,000,000 r