1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Cannot Figure out this method

  1. Oct 6, 2008 #1
    1. The problem statement, all variables and given/known data
    Suppose that you are given the following PetDriver class, which includes a main method:




    public class PetDriver{
    public static void main(String[] args){
    int weight = 40;
    Pet doggie = new Pet("Rover", weight);
    System.out.println("my pet's name is " + doggie.getName());
    System.out.println("my pet's weight is " + doggie.getWeight());
    }
    }

    Executing main produces the following output:

    my pet's name is Rover
    my pet's weight is 40

    Complete the Pet class definition, below, so that the main method shown above works correctly.


    2. Relevant equations



    3. The attempt at a solution
    This is what I tried, but it didn't work:
    public class Pet{
    private String name;
    private int weight;
    public Pet(String who, int pounds){
    name = who;
    weight = pounds;
    }
    public String getName(){return name;}

    public int getWeight(){return weight;}

    }
     
  2. jcsd
  3. Oct 8, 2008 #2

    Mark44

    Staff: Mentor

    You said it didn't work, but didn't give any further information, such as whether there were compiler errors, and if there were no compiler errors, what output did you get.

    This looks like C++ code--is it? The thing that pops out at me is your constructor for your Pet class. You can't use the assignment operator (=) to assign a string to a variable. I haven't done much with C++ for a few years, so I'm not sure whether there are any methods on the String class that you can use to copy a String value to a variable. If there is one, you'll need to use it. If not, you can use some of the older C run-time functions, such as strcpy().

    Mark
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?