How do you update/change a instance variable in Java? (Beginner Level) - java

I am new to java, and I am trying to create a method to update the instance variable age for my objects. I am getting the code to compile, but I am seeing no change in the age value. This code is part of an assignment, so I cannot change the constructors. The method I wrote to update the age (that doesn't work) is shown below. My entire code is shown below that. I am also curious if there's a way to update/change just one of my objects, but before I do that, I need the method to work for both. Any help writing this method properly would be appreciated!
public void setnewAge(int age) {
dogAge += 1;
this.dogAge = dogAge;
}
Below is my entire code (including the method I wrote to update age).
public class Dog {
//Instance Varibles
private String dogName;
private int dogAge;
private int dogWeight;
//Two Contructors (One Completely Empty)
public Dog() {
}
public Dog(String name, int age, int weight){
dogName = name;
dogAge = age;
dogWeight = weight;
}
//Getters
public String getName() { return dogName;}
public int getAge() { return dogAge;}
public int getWeight() { return dogWeight;}
//Setters
public void setName(String theName) { dogName = theName;}
public void setAge(int theAge) {dogAge = theAge;}
public void setWeight(int theWeight) {dogWeight = theWeight;}
//to(String) method
public String toString() {
return "The dogs's name is " + getName() + ", the dogs's age is " +
getAge() + ", " + "\n" + "the dogs's weight is " + getWeight() + ".";
}
public void setnewAge(int age) {
dogAge += 1;
this.dogAge = dogAge;
}
//Main Method
public static void main(String[] args) {
Dog poodle = new Dog("Bob", 5, 26);
System.out.println(poodle);
Dog lab = new Dog();
lab.setName("Steve");
lab.setAge(8);
lab.setWeight(43);
System.out.println(lab);
}
}

As Tom said, you need to actually call the function in your main function otherwise, there will be no change, and also to refine your code for your setnewAge function, try this:
public void setnewAge() {
this.dogAge = dogAge + 1;
}
Then in the main function call setnewAge() and then print your age to see the results.
Dog poodle = new Dog("Bob", 5, 26);
poodle.setnewAge() ;

Related

java Output does not match input for variables

Writing a main class to output from 2 other classes. There are 6 variables being passed but only the last 3 are printing correctly. The first 3 all return null. Here is the output:
DOG DATA
null is a null, a null dog.
The top trick is : Spinner.
The Corgi is 12 years old and weighs 20 pounds.
public class Dog {
// instance variables
public static String type;
public static String breed;
public static String name;
public static String topTrick;
// constructor
public Dog(String type, String breed, String name) {
type = "No type";
breed = "No breed";
name = "No name";
}
// methods
public static String setTopTrick(String trick) {
topTrick = trick;
return trick;
}
// method used to print Dog information
public String toString() {
String temp = "\nDOG DATA\n" + name + " is a " + breed +
", a " + type + " dog. \nThe top trick is : " +
topTrick + ".";
return temp;
}
}
ublic class Corgi extends Dog {
// additional instance variables
public static int weight;
public static int age;
// constructor
public Corgi(String type, String breed, String name, int pounds, int years) {
// invoke Dog class (super class) constructor
super(type, breed, name);
weight = pounds;
age = years;
}
// mutator methods
public static int setWeight(int pounds) {
weight = pounds;
return pounds;
}
public static int setAge(int years) {
age = years;
return years;
}
// override toString() method to include additional dog information
#Override
public String toString() {
return (super.toString() + "\nThe Corgi is " + age +
" years old and weighs " + weight + " pounds.");
}
}
public class Driver {
public static void main(String[] args) {
Corgi sleeper = new Corgi("Geriatric", "Pembroke Welsh", "Ein", 20, 12);
sleeper.setTopTrick("Spinner");
System.out.println(sleeper);
}
}
Literally everything in your program except main that is static should not be static. Static variables are not instance variables.
Also, your Dog constructor is incorrect, and should be
this.type = type;
this.breed = breed;
this.name = name;

Basic JAVA app with setters and setters and increment an integer by 1

I'm just blanking on what to do next.
What I need to do:
The class should have the variables name, breed, age, and color
A constructor that sets all the variables
Getters and Setters for all the variables
A main method that creates an instance of the Dog and utilizes the
constructor
You can pick values you feel appropriate for the variables
Increase the dog's age by 1
Print all the values to the screen
Heres what I've done.
public class DOG {
String DogName;
String DogBreed;
int DogAge;
String DogColor;
public DOG(String name, String color, String breed, int age) {
this.DogName=name;
this.DogColor=color;
this.DogBreed= breed;
this.DogAge=age;
}
public static void main(String[] args) {
DOG myDog = new DOG("Ares","Red","Rott",5);
System.out.println(myDog.DogName+" " + myDog.DogColor+ " " + myDog.DogAge+ " " + myDog.DogBreed);
}
public void addOnetoAge() {
if(DogAge >=6 DogAge++);
}
public String getDogName() {
return DogName;
}
public void setDogName(String dogName) {
DogName = dogName;
}
public String getDogBreed() {
return DogBreed;
}
public void setDogBreed(String dogBreed) {
DogBreed = dogBreed;
}
public int getDogAge() {
return DogAge;
}
public void setDogAge(int dogAge) {
DogAge = dogAge;
}
public String getDogColor() {
return DogColor;
}
public void setDogColor(String dogColor) {
DogColor = dogColor;
}
if(int i=1; i <= myDog.DogAge: i++) {
System.out.println(myDog.DogAge);
};
}
}
I'm just getting back into java and have forgotten what goes where.
I would be grateful for a bit of direction
For the most part, you have the right code, but your two if statements are not necessary, so you should remove both.
If you follow the assignment instructions
Increase the dog's age by 1
Print all the values to the screen
In your main method all you need to do is this
DOG d = new DOG("x", "y", "z", 2);
d.setAge(g.getAge() + 1); // Increase by one
System.out.println(...); // print the values of the getters
This would iterate a range of all the value between one and the dog age, not increase it
for(int i=1; i <= myDog.DogAge: i++) {
This only increases the ages for dogs 6 and older (which seems like a weird design)
if(DogAge >=6) DogAge++;
Edit your method for adding 1 to DogAge
instead of
public void addOnetoAge() {
if(DogAge >=6 DogAge++);
}
use
public void addOnetoAge() {
if(DogAge >=6) DogAge++;
}
also, don't forget to call your addOnetoAge() method when it's time to add 1 to DogAge
You need to place your main method outside of the Dog class. This should work.
public class MainApplication
{
public static void main(String[] args)
{
Dog goodBoy = new Dog("Milou", "Wire Fox Terrier", 6, "White");
System.out.println(goodBoy.getDogName() + " " + goodBoy.getDogBreed() + " " + goodBoy.getDogAge() + goodBoy.getDogColor());
}
}
class Dog
{
private String dogName;
private String dogBreed;
private int dogAge;
private String dogColor;
public Dog(String dogName, String dogBreed, int dogAge, String dogColor)
{
this.dogName = dogName;
this.dogBreed = dogBreed;
this.dogAge = dogAge;
this.dogColor = dogColor;
}
public String getDogName()
{
return dogName;
}
public void setDogName(String dogName)
{
this.dogName = dogName;
}
public String getDogBreed()
{
return dogBreed;
}
public void setDogBreed(String dogBreed)
{
this.dogBreed = dogBreed;
}
public int getDogAge()
{
return dogAge;
}
public void setDogAge(int dogAge)
{
this.dogAge = dogAge;
}
public String getDogColor()
{
return dogColor;
}
public void setDogColor(String dogColor)
{
this.dogColor = dogColor;
}
public void increaseAge()
{
this.dogAge++;
}
}

Java inheritance - subclass method override

I am struggling with an inheritance task in Java
I was given an Animal.java class. My homework is to create a subclass called Lion.java. One of the tasks I'm struggling with within the entire task is outputting the type of Lion it is based on the weight of the lion. This is the code for the Animal.java
public class Animal {
private int numTeeth = 0;
private boolean spots = false;
private int weight = 0;
public Animal(int numTeeth, boolean spots, int weight){
this.setNumTeeth(numTeeth);
this.setSpots(spots);
this.setWeight(weight);
}
public int getNumTeeth(){
return numTeeth;
}
public void setNumTeeth(int numTeeth) {
this.numTeeth = numTeeth;
}
public boolean getSpots() {
return spots;
}
public void setSpots(boolean spots) {
this.spots = spots;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public static void main(String[] args){
Lion lion = new Lion(30, false, 80);
System.out.println(lion);
}
}
This is my code for the Lion.java class so far:
public class Lion extends Animal {
String type = "";
public Lion(int numTeeth, boolean spots, int weight) {
super(numTeeth, spots, weight);
}
public String type(int weight){
super.setWeight(weight);
if(weight <= 80){
type = "Cub";
}
else if(weight <= 120){
type = "Female";
}
else{
type = "Male";
}
return type;
}
#Override
public String toString() {
String output = "Number of Teeth: " + getNumTeeth();
output += "\nDoes it have spots?: " + getSpots();
output += "\nHow much does it weigh: " + getWeight();
output += "\nType of Lion: " + type;
return output;
The problem is the output does not return the type based on the if statement above. It's probably a very simple solution but I can't seem to figure it out.
In toString method, instead of type replace with type() method.
#Override
public String toString() {
String output = "Number of Teeth: " + getNumTeeth();
output += "\nDoes it have spots?: " + getSpots();
output += "\nHow much does it weigh: " + getWeight();
output += "\nType of Lion: " + type(getWeight());
return output;
Take a good look at your Lion constructor
public Lion(int numTeeth, boolean spots, int weight) {
super(numTeeth, spots, weight);
}
This doesn't do anything for the type (your public type method).
In order to set the private type class variable you need to either call the type method in the constructor or after the object has been created but before you call the toString method. For example
public Lion(int numTeeth, boolean spots, int weight) {
super(numTeeth, spots, weight);
type(weight);
}
Note that, as pointed out in the comments, you probably would be better off handling the type directly in the setWeight method. You can do something like
#Override
public void setWeight(int weight) {
super.setWeight(weight);
type(weight);
}
and leave the constructor alone.
Taking it one step further, you could refactor your code such that the type method has no parameter (you've already set the weight member).

Print the value of a Java constructor

I am a java beginner and I am trying to get used to objects. Is there anyway that I can print out the value of a constructor in main? How can I print out the value's Kevin,20? Thanks
public class MainConstructor {
public static void main(String[] args) {
ConstructorClass emp1 = new ConstructorClass("Kevin", 20);
}
}
//Constructor Class
public class ConstructorClass {
private String name;
private int number;
public ConstructorClass(String name, int number) {
this.name = name;
this.number = number;
System.out.println("called");
}
}
Add a toString() method to ConstructorClass:
public String toString() {
return name + "," + number;
}
Then call this from main:
public static void main(String[] args) {
ConstructorClass emp1 = new ConstructorClass("Kevin",20);
System.out.println(emp1.toString());
}
Try using toString() in your class
public String toString() {
return this.name + "," + this.number;
}
and in your main just do emp1.toString(); to print it to your console
Constructor is basically just another method (but for the love of what is holy, never say that during interview or even to your professor) so there is nothing wrong with doing this:
public class ConstructorClass {
private String name;
private int number;
public ConstructorClass(String name, int number) {
this.name = name;
this.number = number;
System.out.println(name+" "+number);
}
}
But this solution is really ugly and kind of "hotfixy". Better solution would be to have constructor to only get the values and have separate method to print what you want:
public ConstructorClass(String name, int number) {
this.name = name;
this.number = number;
}
void printNameAndNumber() {
System.out.println(name+" "+number);
}
And use the class like this in your main
ConstructorClass c = new ConstructorClass("John",85)
c.printNameAndNumber();
Also some people like to handle this by going through hoops and loops and overriding ToString, but that is being too overzealous and there is really no benefit in your case (or any other primitive case).
public ConstructorClass(String name, int number) {
this.name = name;
this.number = number;
System.out.println(name + "," + number);
}
If you want to properly print out those values, you should have getter methods set in your methods
Example below
public String getName(){
return name;
}
public int getNumber(){
return number;
}
Then to print those values, you should then use methods toString() and method print() to display your values
Example
public String toString(){
return getName() + " " + getNumber();
}
public void print(){
System.out.println(toString());
}
Then in the class with the main method, you call your print method for that specific class
Example
ConstructorClass emp1 = new ConstructorClass("Kevin",20);
emp1.print();
Hope this helped, Enjoy :)

How do I print using toString using inheritance in Java

public class StuTest2
{
public static final int NUMBER_OF_STUDENTS = 7;
public static void main(String[] args)
{
Student[] stus = new Student[NUMBER_OF_STUDENTS];
// Student has ID, name, and GPA
stus[0] = new Student(123, "Suzy", 3.9);
// Default for missing GPA will be 9.99 "special value
stus[1] = new Student(234, "Tom");
// Default name will be "Student #xxx" where
// "xxx" is the actual ID number
stus[2] = new Student(456);
// A grad student also has a thesis topic
stus[3] = new GradStudent(567, "Fred", 3.8, "Java");
// Default thesis topic is "Undecided"
stus[4] = new GradStudent(678, "Staci", 3.1);
// Doctoral students earn a stipend
stus[5] = new DoctoralStudent(789, "Mandy", 4.0, "Databases", 3550.00);
// If missing, the default stipend is $3000.00
stus[6] = new DoctoralStudent(890, "Ned", 3.7, "Cisco Networking");
// Inside the loop, the toString method is called for each
// student. All graduate students show the word "Graduate" in
// front of the output from this method.
for(Student stu : stus)
{
}
}
}
class Student
{
private int id;
private String name;
private double gpa;
public Student(int i, String n, double g)
{
id = i;
name = n;
gpa = g;
}
public Student(int i)
{
this(i, "Student #" + i);
}
public Student(int i, String n)
{
this(i, n, 9.99);
}
public int getId()
{
return id;
}
public String getName()
{
return name;
}
public double getGPA()
{
return gpa;
}
public String toString()
{
return System.out.println(stus.getId+", " + stus.getName
+ ", " + stus.getGPA);
}
}
class GradStudent extends Student
{
private String topic;
public GradStudent(int i, String n, double g, String t)
{
super(i, n, g);
topic = t;
}
public GradStudent(int i, String n, double g)
{
this(i, n, g, "Undecided");
}
public String getTopic()
{
return topic;
}
public String toString()
{
return super.getTopic();
}
}
class DoctoralStudent extends GradStudent
{
private double stip;
public DoctoralStudent(int i, String n, double g, String t, double s)
{
super(i, n, g, t);
stip = s;
}
public DoctoralStudent(int i, String n, double g, String t)
{
this(i, n, g, t, 3000.00);
}
public double getStip()
{
return stip;
}
public String toString()
{
return super.getStip();
}
}
I'm trying to print out while using the return super.toString(), but Iget errors saying cannot find symbol for stus, but I have it right before starting the student class. What gives? ps, sorry for the bad closings, trying to meet standards on here lol
Your "stus" variable is only in scope inside the main() method, so you can't access it outside of that method. Furthermore, "stus" is an array, so it doesn't even make sense to call getId on it. Further, notice that getId refers to a variable since it doesn't have parenthesis after it.
Keep in mind that in your toString() method, you're already "inside" a Student Object, so you can just call the getId() function directly:
public String toString()
{
return getId() +", " + getName() + ", " + getGPA();
}
Also note that I've removed the System.out.println() function in your toString method, since it doesn't return anything and therefore doesn't make sense to return anyway.
You've got a lot of incorrect syntax in your code, and I highly recommend starting much smaller. You'll have much better luck if you develop your program incrementally instead of trying to do the whole thing in one shot. I recommend starting over and compiling and testing with every single line you add.

Categories

Resources