Getter/setter methods -- how do I use the return values

I'm just learning Java, and I haven't been to this site since the end of July, I think. I have a question regarding getter and setter methods. I switched to the book Head First Java after a poster here recommended it. I'm only about a hundred pages into the book, so the code I'm submitting here reflects that. It's the beginnings of a program I'd eventually like to complete that will take the entered information of my CD's and alphabetize them according to whatever criteria I (or any user for that matter) choose. I realize that this is just the very beginning, and I don't expect to have the complete program completed any time soon -- it's my long term goal, but I thought I could take what I'm learning in the book and put it to practical use as I go along (or at lest try to).
Yes I could have this already done it Excel, but where's the fun and challenge in that? :) Here's the code:
// This program allows the user to enter CD information - Artist name, album title, and year of release -- and then organizes it according the the user's choice according to the user's criteria -- either by artist name, then title, then year of release, or by any other order according to the user's choice.
//First, the class CDList is created, along with the necessary variables.
class CDList{
     private String artistName;//only one string for the artist name -- including spaces.
     private String albumTitle;//only one string the title name -- including spaces.
     private int yearOfRelease;
     private String recordLabel;
     public void setArtistName(String artist){
     artistName = artist;
     public void setAlbumTitle(String album){
     albumTitle = album;
     public void setYearOfRelease(int yor){
     yearOfRelease = yor;
     public void setLabel(String label){
     recordLabel = label;
     public String getArtistName(){
     return artistName;
     public String getAlbumTitle(){
     return albumTitle;
     public int getYearOfRelease(){
     return yearOfRelease;
    public String getLabel(){
    return recordLabel;
void printout () {
       System.out.println ("Artist Name: " + getArtistName());
       System.out.println ("Album Title: " + getAlbumTitle());
       System.out.println ("Year of Release: " + getYearOfRelease());
       System.out.println ("Record Label: " + getLabel());
       System.out.println ();
import static java.lang.System.out;
import java.util.Scanner;
class CDListTestDrive {
     public static void main( String[] args ) {
          Scanner s=new Scanner(System.in);
          CDList[] Record = new CDList[4];
          int x=0;     
          while (x<4) {
          Record[x]=new CDList();
          out.println ("Artist Name: ");
          String artist = s.nextLine();
          Record[x].setArtistName(artist);
          out.println ("Album Title: ");
          String album = s.nextLine();
          Record[x].setAlbumTitle(album);
          out.println ("Year of Release: ");
          int yor= s.nextInt();
                s.nextLine();
          Record[x].setYearOfRelease(yor);
          out.println ("Record Label: ");
          String label = s.nextLine();
          Record[x].setLabel(label);
          System.out.println();
          x=x+1;//moves to next CDList object;
          x=0;
          while (x<4) {
          Record[x].getArtistName();
          Record[x].getAlbumTitle();
          Record[x].getYearOfRelease();
          Record[x].getLabel();
          Record[x].printout();
          x=x+1;
               out.println("Enter a Record Number: ");
               x=s.nextInt();
               x=x-1;
               Record[x].getArtistName();
            Record[x].getAlbumTitle();
            Record[x].getYearOfRelease();
            Record[x].getLabel();
            Record[x].printout();
     }//end main
}//end class          First, I'd like to ask anyone out there to see if I could have written this any more efficiently, with the understanding that I'm only one hundred pages into the book, and I've only gotten as far as getter and setter methods, instance variables, objects and methods. The scanner feature I got from another book, but I abandoned it in favor of HFJ.
Secondly --
I'm confused about getter and setter methods -- I'd like someone to explain to me what they are used for exactly and the difference between the two. I have a general idea, that getters get a result from the method and setters set or maybe assign a value to variable. I submitted this code on another site, and one of the responders told me I wasn't using the returned values from the getter methods (he also told me about using a constructor method, but I haven't got that far in the book yet.). The program compiles and runs fine, but I can't seem to figure out how I'm not using the returned values from the getter methods. Please help and if you can explain in 'beginners terms,' with any code examples you think are appropriate. It will be greatly appreciated.
By the way, I'm not a professional programmer -- I'm learning Java because of the intellectual exercise and the fun of it. So please keep that in mind as well.
Edited by: Straitsfan on Sep 29, 2009 2:03 PM

Straitsfan wrote:
First, I'd like to ask anyone out there to see if I could have written this any more efficiently, with the understanding that I'm only one hundred pages into the book, and I've only gotten as far as getter and setter methods, instance variables, objects and methods. The scanner feature I got from another book, but I abandoned it in favor of HFJ.Yes, there is tons you could have done more efficiently. But this is something every new programmer goes through, and I will not spoil the fun. You see, in 3 to 6 months when you have learned much more Java, assuming you stick with it, you will look back at this and be like "what the hell was I thinking" and then realize just haw far you have come. So enjoy that moment and don't spoil it now by asking for what could have been better/ more efficient. If it works it works, just be happy it works.
Straitsfan wrote:
Secondly --
I'm confused about getter and setter methods -- I'd like someone to explain to me what they are used for exactly and the difference between the two. I have a general idea, that getters get a result from the method and setters set or maybe assign a value to variable. I submitted this code on another site, and one of the responders told me I wasn't using the returned values from the getter methods (he also told me about using a constructor method, but I haven't got that far in the book yet.). The program compiles and runs fine, but I can't seem to figure out how I'm not using the returned values from the getter methods. Please help and if you can explain in 'beginners terms,' with any code examples you think are appropriate. It will be greatly appreciated.
By the way, I'm not a professional programmer -- I'm learning Java because of the intellectual exercise and the fun of it. So please keep that in mind as well.First, if you posted this somewhere else you should link to that post, it is good you at least said you did, but doubleposting is considered very rude because what inevitably happens in many cases is the responses are weighed against each other. So you are basically setting anyone up who responds to the post for a trap that could make them look bad when you double post.
You are setting you getters and setters up right as far as I can tell. Which tells me that I think you grasp that a getter lets another class get the variables data, and a setter lets another class set the data. One thing, be sure to use the full variable name so you should have setRecordLabel() and getRecodLabel() as opposed to setLabel() and getLabel(). Think about what happens if you go back and add a label field to the CDList class, bad things the way you have it currently. Sometimes shortcuts are not your friend.
And yes, you are using the getters all wrong since you are not saving off what they return, frankly I am suprised it compiles. It works because you don't really need to use the getters where you have them since the CDList Record (should be lowercase R by the way) object already knows the data and uses it in the printout() method. Basically what you are doing in lines like:
Record[x].getArtistName();is asking for the ArtistName in Record[x] and then getting the name and just dropping it on the floor. You need to store it in something if you want to keep it, like:
String artistName = Record[x].getArtistName();See how that works?
Hope this helped, keep up the good learning and good luck.
JSG

Similar Messages

  • How do I use the Index Values property node with a multidimensional array.

    I am using a 2D array to store operator inputs on my front panel.  I only want to display one element to the operator at a time.  I am trying to use the Index Values property node to change the displayed element.  However, I can only get the Rows index to work.  How do I direct the Columns index as well?  The help says to use one per dimension.  I need clarification on what this is talking about.  I've tried adding a second element to the property node, 2 seperate property nodes, and diferent wiring techniques. (series, parallel)

    If you only wire up one of the inputs (col or row) what you get out is a 1D array of either the column or row. If you wire controls to both, then you will get one element out of the array. Getting a single element in a 2D array requires you to specify both a row and column.
    Message Edited by Dennis Knutson on 02-08-2007 08:34 AM
    Attachments:
    Index 2D Array.PNG ‏2 KB

  • How to determine the get/set methods of an element from the schema

    Is there a way that I can obtain the java method call to an element using only the schema (maybe using SchemaTypeSystem, SchemaType, SchemaComponent)? For instance, as I traverse the schema is there a method that I can call that will return:
    "getPurchaseOrder().getCustomer().getName()"
    for the name element in the form of a string or some other representation?
    Thanks in advance.
    Joey

    Sorry Manoj,
    but i didn´t find out, why these programs should be able to solve my issue. They just display a picture using the CL_GUI_PICTURE control.
    I am looking fo a way to resize a given control to the very maximum, so that it fills the whole SAPGUI window!
    Thanks anyway...
    MIKE

  • How can I use the output value from SIMPLE PID to write something to the serial port?

    I am working on my Senior Design Project that requires the use of incoming compressed air, propotional valves, continuous servo motors, and a serial servo motor microcontroller.  I have figured out how to send byte sequences to the microcontroller through LabVIEW using the VISA serial write function.  The motors are attached to the valves to control the flow rate.  I have created my own simple feedback system using a bunch of case structures but I realized that I am basically trying to recreate the wheel (I basically was writing my own PID VI).   I have an older version of LabVIEW (7.0 Express) and theres no way to upgrade or buy the PID toolkit, so I am stuck using the Simple PID VI.  Also, the only way the motor works is sending an array of bytes to tell it to turn on/off, direction, and speed.  Is there any way I can use the Simple PID VI in conjunction with the VISA SERIAL write function, or is there any other way I can communicate with the serial port using this pid vi?  Any information would be appreciated.

    Hi gpatel,
    you know how to communicate to serial port, but you don't know how to send a value from SimplePID to serial port???
    You know how to communicate, but then you don't know how to communicate???
    You should explain this in more detail...
    Edit:
    From you first post you know what values your motor driver is expecting. You know which values the PID.vi is providing. Now all you need is a formula to reshape the values from PID to the motor. It's up to you to make such a formula. Unless you provide any details we cannot give more precise answers...
    Message Edited by GerdW on 02-28-2010 08:35 PM
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome

  • NEWBIE --Get/Set methods HOW??

    I am not understanding what I am doing wrong. I added a variable getName and setname and i got errors. Can someone help??
    //=============================================================================
    //Paul Cote, Jr.
    //Java Programming
    //Fall 2006
    //Programming Project 4.2 PAGE 203
    // Design and implement a class call Dog that contains instance data that
    //represents the dog's name and age. Define the Dog constructior to accept and
    //initiate instance data. Include a method to compute and return the age of
    //the dog in 'person years'(seven times the dog's age). Include a toString
    //method that returns a one-line description of the dog. Create a driver
    //class called Kennel, whose main method instantiates and updates
    //several Dog objects.
    //============================================================================
    import java.util.Scanner;
    class Dog{
         public static void main(String[] args) {
         //info about the dog
         int age;
         String setname;
         String name;
    //public setname()
    //          return name;
         String message;
         Scanner scan=new Scanner(System.in);     
         System.out.println("Enter Dog's Name: ");
         name=scan.nextLine();
         System.out.println("Enter Dog's Age: ");
         age=scan.nextInt();
         System.out.println( "Your dog's name is " +name);
         System.out.println( name+" is "+ age+ " years old.");
         int HumanAge=(age*7);
         System.out.println( name+" is "+ HumanAge+ " human years old.");
    }

    you kinda missed the point buddy;
    import java.util.Scanner;
    class Dog{
    private int age;
    private String name;
    public Dog() {
    //info about the dog
    age = 0; //any default value will do
    name = ""; //any default value will do
    public void setName(String s) {
    this.name = s;
    public String getName() {
    return this.name;
    public static void main(String args[]) {
    String message;
    Scanner scan=new Scanner(System.in);
    System.out.println("Enter Dog's Name: ");
    setName(scan.nextLine());
    System.out.println("Enter Dog's Age: ");
    setAge(scan.nextInt());
    System.out.println( "Your dog's name is " + getName());
    System.out.println( name+" is "+ getAge()+ " years old.");
    int HumanAge=(getAge()*7);
    System.out.println( getName()+" is "+ HumanAge+ " human years old.");
    public static void main(String[] args) {
    }

  • How to get the return value of a method

    hi there
    here is the code i write a method
    public void time(int x,int y){
    int xx;
    int yy;
    xx++;
    yy++;
    x=xx;
    y=yy;
    i want to use the return value of x and y at another place,who can tell if it is possible. thank u very much

    You declare the return type of the method, and then use the return keyword to return a value which you can assign to a variable.
    As the other respondent said, you cannot return more than one value from a function. If you need to return two related values, you may want to enclose them in a class and return an instance of that class. For instance:
    class TimeValue {
       final int x;
       final int y;
    public TimeValue(int x, int y) {
       this.x = x;
       this.y = y;
    }Then your method could create a new TimeValues and return it:
    public TimeValue time(int x,int y){
       int xx = x;
       int yy = y;
       ++xx;
       ++yy;
       return new TimeValue(xx, yy);
    }

  • How to Access the Return Value of a Function

    Hi,
    How do I access the return value when calling an Oracle function from .NET using Oracle.DataAccess.Client? The function returns an integer of 0, 1 or 99.
    Dim db_command_oracle As New OracleCommand()
    db_command_oracle.Connection = db_connection_oracle
    db_command_oracle.CommandType = CommandType.StoredProcedure
    db_command_oracle.CommandText = "swsarsi.import_appointments"
    Dim ret_value As New OracleParameter()
    ret_value.OracleDbType = OracleDbType.Int32
    ret_value.Direction = ParameterDirection.ReturnValue
    ret_value.Size = 2
    ret_value.OracleDbType = OracleDbType.Int32
    db_command_oracle.Parameters.Add(ret_value)
    Dim IN_student_id As New OracleParameter()
    IN_student_id.OracleDbType = OracleDbType.Varchar2
    IN_student_id.Direction = ParameterDirection.Input
    IN_student_id.Size = 10
    IN_student_id.Value = student_id
    db_command_oracle.Parameters.Add(IN_student_id)
    db_command_oracle.ExecuteNonQuery()
    messagebox.show(ret_value) ?????

    Your ODP.NET code looks correct. What error are you seeing?
    One thing that will definitely generate an error is that .NET message boxes require that strings be displayed. ret_value is a parameter object. You need to access its value and convert it to a string. At a minimum, you need to change that.

  • How to dynamically convert the return  datatype of a procedure

    Hi ,
    I want to write a procedure which will take two argument.
    one will be string and another one will be a out variable having dynamic return type based on the data in first passing parameter.
    Description:
    let suppose i have one table which has 3 column
    1.String_col1 varchar2 (it will contain String combination of alphabets,numbers)
    2.number_col2 varchar2 (it will contain numbers only)
    3.date_col3 varchar2 (it will contain DATE)
    All columns are having varchar2 as their datatype.(in sort all are String).
    now i want to write a procedure which will convert the datatype of all the three columns into their respective datatypes i.e.
    1.String_col1 varchar2
    2.number_col2 number
    3.date_col3 date
    Note:I am passing only 1 column in procedure as IN parameter.I dont want to convert 1 row in their respective datatype.
    Please let me know if you want any more information from my side.

    I'm pretty sure that isn't possible.
    What you could do is write a function to determine the datatype of the input, and use the return value of that function in either a decode or case statement to determine which of 3 explicitly defined functions to use.
    Carl

  • How to retreive and display return value from BAPI

    Hello,
    I am using SUP to create a sales order application. In my MBO I have a create operation which calls a BAPI to create a sales order. How can I retrieve the return value (saled doc number) and display it on a screen and display it as an Alert of BB application.
    Regards
    Nidhideep Bhandari

    Hi David Brandow,
    I have tried your solution where I just created a MBO for my 'operation' and I'm using sync parameters to execute the RFC.
    The problem I'm facing is, for example, if I create a record it gets saved in the MBO table and the record successfully gets created in SAP as well after a sync. But when I create another record and sync, the previously saved record in MBO table also gets executed so I'm getting duplicate entries in SAP.
    Have you or anyone faced this problem?
    Any response is appreciated. Please let me know if I'm not clear, I realized its a complicated scenario.
    Thanks,
    Sandeep

  • HTMLDB_ITEM.SELECT_LIST the the return values

    All
    Looking over the docs it states that p_value should be the value you want to show by default, so if you did not put your primary key in this field and just entered one of the texts in p_list_values and wanted to use the return value of p_list_values how would you access it.
    Example.
    select HTMLDB_ITEM.SELECT_LIST(1,'keep','Keep;accid,Delete;accid')
    This would make keep the default selected, but when you pass this to a process, how do you tell if the user selected keep or delete and then pull out the primary key value accid, so that you can update or delete the table.

    I was able to work through this problem. Thank You.

  • Using javascript return values in links

    Can anyone please tell me if there is a way to use the return value from a javascript function as a parameter in a link?
    Thanks,
    Chris

    You mean in PFR of controller , ie after user selects a record from LOV window and after its populated back into to the textItem on the main entry form ??
    The value is displayed correctly in the intended textItem which has viewInstance and viewValue attached to it .
    so this is what setup looks like
    Entry form
    Customer Name - lov
    Customer Number(d) - Display Only - Populated by Lovmappings from LOV - mapped to Customer Number attribute on LOV window. It also has viewInstance and ViewAttrib assigned to it .
    Save Action
    At this point of time , i am assuming i already have value in Customer Number(d)since its displayed on the screen,rite ??
    or Do i have to take the value in formValue and then explicitly do a setAttribute to set that value to view object /Customer Number(d)
    hope this helps to understand the scenario

  • Change the properties of a field dynamically using Getter/Setter methods

    Thanks
    Raj
    Edited by: RajICWeb on Aug 12, 2009 4:31 AM

    Hi Harshit
    Thanks for the reply. Like you suggested, I redefined the get_i_zfield( ) method. But the program is not going through this method.
    FYI.....I created the getter/setter methods manually for my zfield. Plz let me know if I am missing anything. Your help will be greatly appreciated.
    Below is my requirement:
    I need to add an additional column (zfield) to a tree view. The name of the component is BTRESTREE. (there is only one view in this component- this view is having only one context node).
    I tried adding my zfield to the attributes (of the context node) through the wizard by right clicking on the 'Attributes'. But I am not getting the 'Create' Option.
    I posted a thread few days back regarding the same problem. One of the experts (Vikash Krishna) suggested me to add some my zfield by redefining the 'GET_TABLE_LINE_SAMPLE' method. As per his suggestion, I was finally able to see my zfield in
    the configuation tab.
    Now, I have to change the properties of my zfield (make this column editable) in the tree view. For that, the only option that I can see is to change the get_i_zfield( ) method (here we have 'rv_disabled') for my zfield. For this, first I need to add my zfield to the Attributes. To achieve this, I added getter/setter methods manually in the Proxy class.
    Thanks
    Raj

  • How should i use the two results sets in one single report data region?

    Hi frnz,
     I have to create a report using the below condition...
    Here my given data  set query gives you the two result sets ,so how should i use that two result sets information in single report....when i accessing that data set query it will take the values off the first result set not for the second result set.
    without using sub report and look up functionality..... if possible
    is there any way to achieve this.....Please let me know..
    Thanks!

    You cant get both resultsets in SSRS. SSRS dataset will only take the first resultset
    you need to either create them as separate queries or merge them into a single resultset and return with ad additional hardcoded field which indicates resultset (ie resultset1,resultset2 etc)
    Then inside SSRS report you can filter on the field to fetch individual resultsets at required places. While merging you need to make sure metadata of two resultsets are made consistent ie number of columns and correcponding column data types should be same.
    In absence of required number of columns just put some placeholders using NULL
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • TA38556 I am trying to set up my apple tv using the hospital network. I am able to detect the network and chose it. But the way the system works is that you have to agree to the terms and conditions of using their network. How do I accomplish this with ap

    I am trying to set up my apple tv using the hospital network. I am able to detect the network and chose it. But the way the system works is that you have to agree to the terms and conditions of using their network before access the internet. How do I accomplish this with apple? Please help.

    There are some other options to you, if you're not at home and nobody is using your router you could set it up at the hospital, if this isn't an option you could get a second router and use it.  Many ethernet routers are available on the cheap, and ethernet cables are cheap too.
    Also, a macbook can share it's internet via the built in wifi it has.  See this go to settings-sharing-internet sharing and configure as desired.  This may require an internet connection via ethernet.  But you should be able to create a wifi network for using something like airplay/home sharing.

  • How do I use the time capsule to share itunes music between multiple apple devices? Also, is it possible to control the music on one device using another, and how do you set this up?

    How do I use the time capsule to share itunes music between multiple apple devices? Also, is it possible to control the music on one device using another, and how do you set this up?

    unless i'm missing something, i think you got mixed up, this is easy google for walk throughs
    i'm assuming this is the new 3tb tc AC or 'tower' shape, if so, its wifi will run circles around your at&t device
    unplug the at&t box for a minute and plug it back in
    factory reset your tc - unplug it, hold down reset and keep holding while you plug it back in - only release reset when amber light flashes in 10-20s
    connect the tc to your at&t box via eth in the wan port, wait 1 minute, open airport utility look in 'other wifi devices' to setup the tc
    create a new wifi network (give it a different name than your at&t one) and put the tc in bridge mode (it may do this automatically for you, but you should double check) under the 'network' tab
    login to your at&t router and disable wifi on it
    add new clients to the new wifi network, and point your Macs to the time machine for backups

Maybe you are looking for