How can I fix my Pet class to work with the given PetDriver class?

  • Thread starter Thread starter Bellatrix6
  • Start date Start date
  • Tags Tags
    Figure Method
AI Thread Summary
The discussion focuses on fixing the Pet class to ensure compatibility with the provided PetDriver class. The initial implementation of the Pet class appears correct, but it is suggested that there may be issues related to the language used, as the syntax resembles C++. The main concern raised is the assignment of the string in the constructor, which may not be valid in C++. Clarification is requested regarding any compiler errors or output received when running the code. The conversation emphasizes the need for proper string handling in the Pet class constructor.
Bellatrix6
Messages
1
Reaction score
0

Homework Statement


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.


Homework Equations





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;}

}
 
Physics news on Phys.org
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
 

Similar threads

Replies
2
Views
1K
Replies
5
Views
3K
Replies
12
Views
2K
Replies
7
Views
3K
Replies
6
Views
2K
Replies
1
Views
3K
Replies
1
Views
1K
Back
Top