Accessor and Mutator Methods

I'm currently learning how to use different types of methods within my program.
One of the things that I'm getting stuck on is how to get user input and then feed that into a new instance of the class that I made.
Here is my cat class
public class Cat
     private String name;
     private int age;
     private double weight;
     private String breed;
     private boolean declawed;
     private double percentGrowthRate;
     public void setName(String name)
          this.name = name;
     public void setAge(int age)
          this.age = age;
     public void setWeight(double weight)
          this.weight = weight;
     public void setBreed(String breed)
          this.breed = breed;
     public void setDeclawed(boolean declawed)
          this.declawed = declawed;
     public void setDeclawed() // This will get overloaded later
     public void Display()
          System.out.printf("Name: %s\n Age: %d\n Weight: %f\n Breed: %s\n Declawed: %b\n", this.name, this.age,
               this.weight, this.breed, this.declawed);
}And here is my Driver program
import java.util.Scanner;
public class CatDriver
     public static void main(String[] args)
          String catName = "";
          int catAge = 0;
          double catWeight = 0.0;
          String catBreed = "";
          boolean catDeclawed = false;
          Cat cat1, cat2, cat3;
          Scanner stdIn = new Scanner(System.in);
          System.out.print("Enter the name of your cat: ");
          catName = stdIn.nextLine();
          cat1 = new Cat(); // this is the part I'm having trouble with
          System.out.printf("How old is %s: ", catName);
          catAge = stdIn.nextInt();
          cat1.setAge(catAge);
          System.out.printf("How much does %s weigh: ", catName);
          catWeight = stdIn.nextDouble();
          cat1.setWeight(catWeight);
          System.out.printf("What breed of cat is %s: ", catName);
          catBreed = stdIn.nextLine();
          cat1.setBreed(catBreed);
          System.out.printf("Has %s been declawed: ", catName);
          catDeclawed = stdIn.nextBoolean();
          cat1.setDeclawed(catDeclawed);
          cat1.Display();
     } // end main
} // end classWhat I tried doing first was saying
Cat catName = new Cat();But that gave me an error and wouldn't work. So my first question is how do you get input from the user and then name an instance of a class after that input (I don't even know if I'm saying that right but hopefully someone understands ><). I want the user to enter the name Gus and then have it create a new instance of the Cat class called Gus.
My second question is, when the code is compiled and run as is, I have some sort of format error when it gets time to ask me the cat's breed. I get asked for the breed AND the declawed on the same line and never have a chance to put in the breed. I can't see any reason why it would do this so anyone who could clear that up also would be appreciated.

Alright. I think I see what you mean.
System.out.print("Enter the name of your cat: ");
          catName = stdIn.nextLine();
          cat1.setName(catName);I added the last line there and now my output returns the name of the cat instead of null. Let me refine my question a little now.
The program works perfectly if I only have 1 cat but let's say I want to enter 3 cats, or even have a loop that will let me enter as many cats as I want. Am I going to have to keep changing my cat variables
Cat cat1, cat2, cat3;To include the number of cats that I expect to run through? I could do it that way and then just reproduce all the above code changing cat1 to cat2, cat3, etc. but it seems like there has to be a better way to do it.

Similar Messages

  • Accessor vs Mutator methods

    Nowadays I'm studying for SCJP 5.0 and I found a strange definition about Encapsulation .
    When I have seen the "Accessor methods"
    To me, it would be related with the both "setters" and "getters" methods
    But on a mock I found this definition:
    "Accessor methods are used to read data members; mutator methods are used to set data members. The mutator methods can validate the parameter values before the values are used to change the state of the internal data model."
    on the mock this sentence would be strong:
    "Accessors methods are used to prevent fields from being set with invalid data."
    the correct would be:
    "Mutator methods are used to prevent fields from being set with invalid data."
    In order to do the exam, how the Sun call that methods?
    - setters and getter methods?
    - Accessor methods and Mutator methods?
    - or only Accessor methods for the both?
    Message was edited by:
    oalexandrino

    I asked that question because I found the following one on the example of mock:
    A class can not be called "tightly encapsulated" unless which of the following is true?
    a.      All member fields are declared final.
    b.      The class is not anonymous.
    c.      The internal data model can be read and modified only through accessor and mutator methods.
    d.      The class is an inner class.
    e.      None of the above
    I think it would be found in:
    Section 5: OO Concepts
    all right?

  • COM+ Event System failed to fire the StartShell and Logon method after installation of PM 1.43

    Hi Guys,
    After installation of Power Manager 1.43, the following errors were immediate shown at event viewer: COM+ Event System failed to fire the StartShell and Logon method on subscription {F6FE5592-FCBC-44AD-A836-D37F5085ED5B}-{00000000-0000-0000-0000-000000000000}-{00000000-0000-0000-0000-000000000000}.  The subscriber returned HRESULT 80004001.
    Please advice if this is a known issue? Thanks!

    Hello,
    this is a known problem. See this thread
    Follow @LenovoForums on Twitter! Try the forum search, before first posting: Forum Search Option
    Please insert your type, model (not S/N) number and used OS in your posts.
    I´m a volunteer here using New X1 Carbon, ThinkPad Yoga, Yoga 11s, Yoga 13, T430s,T510, X220t, IdeaCentre B540.
    TIP: If your computer runs satisfactorily now, it may not be necessary to update the system.
     English Community       Deutsche Community       Comunidad en Español

  • Abstract class with set and get methods

    hi
    how to write set and get methods(plain methods) in an abstartc class
    ex: setUsername(String)
    String getUsername()
    and one class is extending this abstract class and same methods existing in that sub class also..... how to write......plz provide some ideas
    am new to programming....
    asap
    thnx in advance

    yes... as i told u.... i am new to coding......
    and my problem is ..... i have 2 classes one is abstract class without abstract methods.. and another class is extending abstract class.....
    in abstract class i have 2 methods...one is setusername(string) and getusername() ..... how to write these two methods.... in abstract class i have private variables username...... when user logins ..... i need to catch the user name and i need to validate with my oracle database and i need to identify the role of that user and based on role of that user i need to direct him to appropriate jsp page.......
    for that now i am writing business process classes..... the above mentioned two classes are from business process.....
    could u help me now
    thnx in advance

  • I want to transfer all my iPhoto, iTunes, contacts, etc. files from my MacBook, which I am selling to a MacBook Pro. What is the easiest and safest method of achieving this? Can the files backed up on Time Machine be transferred to the Pro?.

    I want to transfer all my iPhoto, iTunes, contacts,documents, etc. files from my MacBook, which I am selling, to a MacBook Pro. What is the easiest and safest method of achieving this? Can the files backed up on Time Machine from the MacBook be transferred to the Pro in some way? I would like to capture the files as they appear on the MacBook, such as "Events" in iPhoto and the various song categories within iTunes without having to rename them all once saved on the Pro, which is the case with photos when I simply save them to thumb drive and import them to the Pro. Sny advice would be appreciated.
    Best regards,
    Rob.

    Michael,
                 Thanks for all your assistance. There is no need for apologies, Migration Assistant did indeed create a second account for the MacBook data. It has just taken me some time to figure out how to access it. I now have all the MB data in one account and the MBP files in another, which suits me fine. In fact, it is an advantage in my case as it keeps the private and business aspects separated.
    I will however try the fatcatsoftware to transfer all the iPhoto files to my iMac, where I keep my main photo library. and it will be of help to keep the events, etc in the transfer. As far as iTunes is concerned, I have HomeSharing on all my computers and this has obviated the need to worry about playlists being transferred successfully. However, HomeSharing did not appear to share the iPhone/iPod apps that were stored on the MB and although these have now come across with the new MacBook account on the MBP, I was wondering whether my iPhone and iPod will be recognised by the MBP and sync with it? Will I need to have the MB account open to achieve this or will the MBP recognise and sync with the iPhone/iPod automatically irrespective of which account is open?
    Thanks for the tip on deauthorising my iTunes account from the MB before sellng. This I will do and I believe the best way to remove all of my data from the hard drive is to reinstall the MacOSX operating system software. Is this the right approach to securely delete everything?
    Thanks again for sharing your expertise and your guidance through this exercise.
    Best regards,
    Rob.

  • Dynamic creation of class and calling methods

    I've got and interface called Transformation and then two implementations called TxA and TxB, where TxA and TxB have their own attribtues and setter and getters for these attributes.
    The question is, I need to create instances of TxA and TxB and called the setter and getters where I at runtime I only know the attribute to set, how can I create and instance and call the right getters and setters methods?
    Thanks in advance

    Smart money says your design sucks and needs to be rethought entirely. Can we get specifics?
    Drake

  • Error in CALL TRANSACTION and SESSION Method

    I have 8 records (1,2,3,4,5,6,7,8) to update into SAP database using CALL TRANSACTION and SESSION Method. If there is a error in 6th record. What happens in both call transaction and session method.
    Please let me know which records will process and what about the error record. How to process only the error record if all other records have updated into database.

    Hi Patil_sumeet,
    if your code for this is not protected secret of some federal agency, you may read [How to post code in SCN, and some things NOT to do...|How to post code in SCN, and some things NOT to do...; and then post relevant lines here.
    According to the facts presented until know it may have been better to ask Radio Eriwan
    Regards
    Clemens

  • HT2729 i have been trying to copy videos from my pc to ipad but it is not working .. i have tried the "drag and drop method and even add files to library but to no avail please help

    please help me regarding moving videos from pc to ipad .. i have ipad 2 wih ios5 and windows xp.. ihave tried add files to library and drag and drop method but they are not working.. what should i do

    Are you trying to add videos to itunes or to your ipad from itunes.
    Your question is very confusing.

  • Where can I get accessories and power adapter for Powerbook 180c

    My father just bought me second hand a Powerbook 180c. It looks to be in great condition. But it can't be checked to make sure as the battery is dead and the power adapter was not with it. I've looked on line at various stores, Office Depot, Staples, Amazon, Buy, etc only to find that they either do not carry Apple products or the accessories and power adapters would not work. Or the prices are disgustingly high. Due to illness I cannot work and my parents are on a limited budget. Does anyone know what sites carry accessories and power adapters that will work on the 180c without breaking the bank, atleast a power adapter for now, to see if the 180c even works? Any advice appreciated.

    Hi, I'm not sure that a retail store will still carry an adaptor this old unless it's a generic one.
    I just checked mine, as Jan says it is 7.5V DC at 3.0A don't get the older version which was for older PowerBooks as it was only 2.0A. The part number on my 3.0A is M5652.
    This fellow on eBay seems to have lots.
    http://cgi.ebay.com/MACINTOSH-POWERBOOK-AC-ADAPTER-M5652-140-180W0QQitemZ190237344088QQihZ009QQcategoryZ101265QQrdZ1QQssPageNameZWD1VQQcmdZViewI temQQtrksidZp1638Q2em118Q2el1247
    Kevin

  • Housebank and payment method for vendor

    Hi
    While doing MIRO, i want housebank and payment method to populate from vendor master data.  I maintained both these details in VM data but its not populating automatically in MIRO.  Please help.  (m using ECC 6)
    Sadhana

    Thanks Rinku.
    If we keep house bank and payment method fields blank while doing data entry, system will pick them up from VM data at the time of payment run. Right??
    But if the housebank field is mandatory for data entry (as in my scenario),  then we have no option but to fill the fields up at the time of MIRO or FB60.
    In my scenario, daily there are 150 bills processed at one centre, and the user has to fill up these two fields every time.  Is there any other solution so that this trouble can be saved?
    Thanks (points assigned).

  • Why does a find and replace method remove whitespace?

    I have method that searches for a string in a FM document and replaces it with a variable. If for example, there was a string foobar that I wanted to replace with the variable barfoo. Then, I expect this text:
    Lorem ipsum dolor sit amet, foobar consectetur adipiscing elit. Vivamus sed purus urna, ac tristique tortor. Nam auctor tellus non enim pulvinar a vestibulum neque tincidunt.
    To be changed to this text:
    Lorem ipsum dolor sit amet, barfoo consectetur adipiscing elit. Vivamus sed purus urna, ac tristique tortor. Nam auctor tellus non enim pulvinar a vestibulum neque tincidunt.
    However, while the text does do the replace it also removes the whitespace between the variable and the text that appears right after the variable so it actually looks looks like this:
    Lorem ipsum dolor sit amet, barfooconsectetur adipiscing elit. Vivamus sed purus urna, ac tristique tortor. Nam auctor tellus non enim pulvinar a vestibulum neque tincidunt.
    Why is the find and replace method removing the whitespace and how do I prevent that from happening? The method is provided below.
    function FindAndReplaceString(pDoc, findString, replaceVariable)
        if (typeof pDoc != 'undefined'&&typeof findString != 'undefined'&&typeof replaceVariable != 'undefined'&&pDoc.ObjectValid()&&findString.length>0&&replaceVariable.length>0)
            var vVarFmtStatus=checkVarFmStatus (pDoc, replaceVariable);
            if (vVarFmtStatus=='In Doc')
                var tr = new TextRange();
                var findParams = new PropVals();
                var frame = pDoc.MainFlowInDoc.FirstTextFrameInFlow;
                var restoreTR = pDoc.TextSelection;
                tr.beg.obj = tr.end.obj = frame.FirstPgf;
                tr.beg.offset = tr.end.offset = 0;
                findParams = AllocatePropVals(1);
                findParams[0].propIdent.num = Constants.FS_FindText;
                findParams[0].propVal.valType = Constants.FT_String;
                findParams[0].propVal.sval = findString;
                tr = pDoc.Find(tr.beg, findParams);
                var vLoopCounter=0;
                while(FA_errno === Constants.FE_Success&&vLoopCounter++< 1000)
                    pDoc.TextSelection = tr;
                    pDoc.Clear(0);
                    var newVar = pDoc.NewAnchoredFormattedVar(replaceVariable, tr.beg);
                    var varLength = newVar.TextRange.end.offset - newVar.TextRange.beg.offset;
                    tr.beg.offset += varLength;
                    tr = pDoc.Find(tr.beg, findParams);
                if (vLoopCounter>0)
                    Log (vLogFileName, 'In the document \''+pDoc.Name+'\', the string \''+findString+'\' was replaced with the variable \''+replaceVariable+'\' '+vLoopCounter+' times.\n')
                if (vLoopCounter>1000)
                    recordErrors (vErrorLog, 'ERROR: In the document "'+pDoc.Name+'", the find and replace operation was stopped after executing '+vLoopCounter+' times. The term being searched for is "'+findString+'" the replacement variable is "'+ replaceVariable+'".')
                pDoc.TextSelection = restoreTR;
                pDoc.ScrollToText(restoreTR);
                } else {
                    recordErrors (vErrorLog, 'ERROR: The find and replace operation failed because the variable '+replaceVariable+' does not exist in the following doc: '+pDoc.Name)
            } else {
                recordErrors (vErrorLog,'Invalid or unitialized parameter passed to function FindAndReplaceString')

    Hi,
    Not at the moment. Please post in http://forums.adobe.com/community/muse/ideas so other users can vote on the feature request.
    Thanks,
    Abhishek

  • HashSet get() and contains() methods, by value or reference?

    All the tutorials I've seen on HashSets use Strings as the object type. With Strings, it seems the get() and contains() methods work by value, not by reference.
    <CODE>
    String s1 = "dog";
    String s2 = "cat";
    String s3 = "dog";
    HashSet<String> set = new HashSet<String>();
    set.add(s1);
    System.out.println(set.contains(s1)); //true;
    System.out.println(set.contains(s2)); //false
    System.out.println(set.contains(s3)); //true
    </CODE>
    But when I use a custom object, it works by reference:
    <CODE>
    MyClass c1 = new MyClass("dog", 1);
    MyClass c2 = new MyClass("cat", 1);
    MyClass c3 = new MyClass("dog", 2);
    MyClass c4 = new MyClass("dog", 1);
    HashSet<MyClass> myClassSet = new HashSet<MyClass>();
    myClassSet.add(c1);
    System.out.println(myClassSet.contains(c1)); //true
    System.out.println(myClassSet.contains(c2)); //false
    System.out.println(myClassSet.contains(c3)); //false
    System.out.println(myClassSet.contains(c4)); //false
    </CODE>
    ("MyClass" is a simple class that holds a String and an int).
    Is there any way I can get the set to select by value rather than reference for objects that aren't String?
    If so, is it possible that the value test could be customised, so that, for example, the above will return true if the String in MyClass is the same, regardless of the int value?

    803559 wrote:
    With Strings, it seems the get() and contains() methods work by value, not by reference.
    String s1 = "dog";
    String s2 = "cat";
    String s3 = "dog";
    System.out.println(set.contains(s1)); //true;
    System.out.println(set.contains(s2)); //false
    System.out.println(set.contains(s3)); //true
    Is there any way I can get the set to select by value rather than reference for objects that aren't String?Warning: Never use the term "by reference" around Java geeks. It makes 'em go all green at the gills and they start muttering about 'bloody C++ crossovers'.
    However, as DrClap pointed out, you've mis-diagnosed the problem:
    System.out.println(s1 == s1);
    System.out.println(s1 == s2);
    System.out.println(s1 == s3));would print out the exact same results.
    For an explanation why, Google "Java String pool" or try [url http://stackoverflow.com/questions/3297867/difference-between-string-object-and-string-literal]here.
    If so, is it possible that the value test could be customised, so that, for example, the above will return true if the String in MyClass is the same, regardless of the int value?Absolutely. But, as others have said, you'd need to override equals() and hashCode().
    Winston

  • Write a servlet without doGet() and doPost() methods

    Hi,
    Can we write a servlet without doGet() and doPost() methods ?

    public class MyCoolServlet extends HttpServlet
    public void init(ServletConfig servletConfig) throws ServletException
    public void service(HttpServletRequest request, HttpServletResponse response)
         throws ServletException, IOException
    // your code here
    }Just an example on how to do it.
    A servlet is loaded by server (before any request). It will run the init function. Then pick up an request, spawn a thread and put this servlet code into the thread, give it session, request and response objects, then call serivce.
    Remember that init is called before, outside the thread, while service is inside the thread and the last to be called. Nice place to put your code.
    If you need to have some sort of init function to be called first on every request PR USER, then make your own function, and call it first in service method.
    Stuff that are put in init() function might only get runned once in the entire server lifetime. Until restart.

  • Help with constructors, accessors and mutators

    Hi all...
    Can anyone give me a code for the following problem with the use of constructors, accessors and mutators ?
    Programme is :
    Create a class called Stock that has the following attributes:
    STKID : integer
    DESC : STRING
    COSTPRICE : float
    SALEPRICE : float
    QTY : integer
    Create constructors, accessors and mutators for the above class.
    Create an array of object that can store up to 100 of the above objects.
    Implement the following functionalities:
    Add new Stock Record
    Search Stock Record
    Delete Stock Record
    Update Stock Record
    Its quite urgent, since I got to submit this for my interview tomorrow. So if anyone knows the code please do reply. Thanks in advance.
    Thanks and Regards,
    Jayanth.

    @jayanth: Ignore these guys - they're just sour and don't understand the value of helping each other out. Besides, I'm bored, and this was an easy write-up. I can send the code to your email ([email protected]) if you'd like. Just let me know.

  • Re: No G/L accounts are defined for bank ICICI and payment method C

    < MODERATOR:  Message locked.  Please read [this|Before you post: Rules of Engagement; before posting next time. use an appropriate subject...  something other than what was copied from an email would be appreciated. >
    Hi Friends,
    When i am doing T.Code F-58 i am getting an error of
    (No G/L accounts are defined for bank ICICI and payment method C) so could anybody please help me how to solve this problem awaiting for your reply friends.
    Points will be assigned.
    Thanks in advance.
    KUMAR.

    Hi Kumar,
    You will have to configure the House Bank with T Code FI12 and further mention the payment method in FBZP. You will have to select one of the  follwing as payment method, check/transfer/postal giro transfer/bill of exchange. Though check (C) is widely used.
    Assign points, if useful.
    Regards,
    Saurabh Agarwal

Maybe you are looking for

  • Delivery line items:

    Dear Guru's, How to restrict the user from adding a new line item in the delivery order, system should not allow if any one tries to enter new line item at the delivery level. System should allow only the line items created in the sales order. Skumar

  • Email messages containing PDF's with hyperlinks

    When I create my PDF (from indesign) with web links and email hyperlinks and send an email that contains the attached PDF, is there a way to allow the recipient to be able to click on those links in that PDF, from within the email message window? Tha

  • I need help with my account since moving

    I have termianted two lines on our account and still ahve one--- I called from the airport on OCTOBER 15th and spoke with three reps about terminating my serice on the two lines. We moved to an area in the Middle East with no VERIZON sevice--- we wer

  • How to translate many to many  with association class

    hello I have found that there is many way to translate this to java code ,could you please tell me what do you think about this. is it right ??is it the best way ?? The relation between A and B is a bidirectional Class A: -idA ClassB: -idB Class C: -

  • Itunes cannot cannot see sim

    Hi all, My brotherin law gave me his old phone on O2 its an iphone 3gs. I am on vodafone and as such went to the shop in my town where they proceed to unlock it.I had a few problems with it not working propery so I looked into it and found out a few