Skip to Main Content

New to Java

Accessor and Mutator Methods

707697Jun 25 2008 — edited Jun 25 2008
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 class
What 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.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jul 23 2008
Added on Jun 25 2008
16 comments
376 views