Java: How to increase the warrior's level? - java

So the output for the warrior's level is not increasing as their experience go up. Warrior 1 starting level is 20 and warrior 2 is 18. I'm trying to increase each warrior's level by printing it out on Game.java file. I tried to increment the expLevel and then experience but it shows an error. What is the best way to increase each of the warrior's level?
public class Game {
public static void main(String[] args) {
// Part 3 of ICE16 then ICE17 edition
// List of weapons
Weapon mean = new Weapon("Mean Words", 1, "Mean words cause very little damage", 4);
Weapon bat = new Weapon("Baseball Bat", 10, "Some properties get destroyed", 4);
Weapon gun = new Weapon("Handgun", 100, "Stronger than a baseball bat", 4);
Weapon bazooka = new Weapon("Bazooka", 200, "Major destruction", 4);
Weapon laChancla = new Weapon("La Chancla", 4000, "Total annihilation", 4);
// Warriors
Warrior w1 = new Warrior(28, "Skeletor", 20, mean);
Warrior w2 = new Warrior(19, "Striker", 18, bat);
// Changes
for (int i = 0; i < 4; i++) {
w1.attack();
w2.attack();
}
w1.attack();
w1.assignWeapon(bazooka);
w2.attack();
w2.assignWeapon(laChancla);
w1.attack();
System.out.println(w1.getExpLevel());
System.out.println(w2.getExpLevel());
}
}
Here is a warrior class:
public class Warrior {
// Part 2 of ICE16 then ICE17 edition
// 4 properties: int age, String name, int expLevel, Weapon weapon
private int age;
private String name;
private int expLevel;
private Weapon weapon;
private int experience = 0;
// Create a constructor that assigns each value to the property
public Warrior(int age, String name, int expLevel, Weapon weapon) {
this.age = age;
this.name = name;
this.expLevel = expLevel;
this.weapon = weapon;
}
// Method 1
public void attack() {
System.out.println("Warrior, " + name + " with experience level " + expLevel + " attacks!");
// Call the strike method from the weapon class
this.weapon.strike();
if (weapon.strike()) {
experience++;
}
if (experience >= 4) {
expLevel++;
} else {
System.out.println("The warrior cannot attack");
}
}
// Method 2
public void assignWeapon(Weapon weapon) {
this.weapon = weapon;
System.out.println(this.name + " now has " + weapon.getType());
}
public int getExpLevel() {
return expLevel;
}
}
Here is a weapon class:
public class Weapon {
// Part 1 of ICE16 then ICE17 edition
// 3 properties: String type, int power, and String strikeMessage
private String type;
private int power;
private String strikeMessage;
private int health = 4;
// In class Weapon, create a constructor that assigns values to each of these internal private properties of the class in the order above.
public Weapon (String type, int power, String strikeMessage, int health) {
this.type = type;
this.power = power;
this.strikeMessage = strikeMessage;
this.health = health;
}
// Method 1
public int getPower() {
return power;
}
// Method 2
public boolean strike() {
System.out.println("Weapon of type " + type + " has power " + power);
System.out.println(strikeMessage);
if (health < 0) {
System.out.println("Weapon " + this.type + " cannot strike because it's damaged");
return true;
} else {
health--;
return false;
}
}
// Method 3
public void setPower(int power) {
this.power = power;
}
// Weapon's Health Level
public String getType() {
return type;
}
}

Your code to increase explevel is within an if statement that will only increase the explevel if the explevel is already 4 or greater.
This means that all Warrior instances with a level of 3 or lower can never increase their level (until you change this code).

Related

Pet BAG Assignment(Class file in Java)-Cannot run the program in Eclipse IDE through apporto

The image is the error message i get as well as showing the eclipse IDEThe problem I am having is I cant get my code to run through the eclipse IDE each time I click run it doesn't run and just gives me an error message "The selection cannot be launched, and there are no recent launches." I am trying to create a PET class file through java.
here is the code for my assignment:
import java.util.Scanner;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Map;
public class Pet {
private String petType;
private String petName;
private int petAge;
private Map<Pet, Integer> dogSpace; // contains the Pet and days it is staying
private Map<Pet, Integer> catSpace; // same but for cats
private int daysStay;
public double amountDue;
/**
* Pet, base class for Dog and Cat
* #param String name - Name of the Pet
* #param int age - Age of the Pet
* #param String type - Cat | Dog
*/
public Pet(String name, int age, String type) {
this.petName = name;
this.petAge = age;
this.petType = type;
this.dogSpace = new HashMap<Pet, Integer>(); // use a hashmap to keep track of pets in the shelter
this.catSpace = new HashMap<Pet, Integer>(); // the Pet object is the key, and the days they are staying is the value.
}
public void checkIn(Pet pet) {
Scanner in = new Scanner(System.in);
System.out.println("How many days will your " + this.petType + " be staying?");
int days = (int) in.nextInt();
this.daysStay = days;
switch(this.petType) {
case "Dog":
if(days > 1) {
System.out.println("Do you require grooming services?");
String needsGrooming = in.next();
boolean grooming;
if(needsGrooming.equals("yes") || needsGrooming.equals("y")) {
System.out.println("We will groom your dog...\n");
grooming = true;
}
else {
grooming = false;
}
this.checkInDog((Dog) pet, days, grooming); // handle the special dog cases
}
else {
this.checkInDog((Dog) pet, days, false);
}
break;
case "Cat":
if(this.catSpace.size() < 12) {
this.catSpace.put(pet, days);
}
break;
default: // Throw an exception if a pet other than a Cat | Dog is booked.
in.close(); // Close the scanner before exiting.
throw new RuntimeException("Sorry, we only accept cats and dogs");
}
in.close(); // Close the scanner when there is no exceptin thrown.
}
/**
* Contains extra steps for checking in a dog.
* #param pet - The dog object.
* #param days - Number of days staying.
* #param grooming - Whether or not the dog needs grooming.
*/
private void checkInDog(Dog pet, int days, boolean grooming) {
pet.setGrooming(grooming);
try {
if(this.dogSpace.size() < 30) { // Enforce the maximum of 30 dogs in the shelter.
this.dogSpace.put(pet, days);
pet.dogSpaceNbr = this.dogSpace.size() + 1;
pet.setDaysStay(days);
}
}
catch (Exception e) { // For some Map objects, calling size() on an empty collection can throw an error.
System.out.println("You're our first visitor!");
System.out.print(pet);
this.dogSpace.put(pet, days);
pet.dogSpaceNbr = 1;
}
System.out.println("" + pet.getPetName() + " will miss you, but is in good hands.");
}
/**
* Check out the desired Pet and calculate how much is owed for the boarding.
* #param pet - The pet you wish the check-out.
* #return amountDue - The amount of money owed for the boarding.
*/
public double checkOut(Pet pet) {
double fee;
if(pet.getPetType() == "Dog") {
double groomingfee = 0.0;
Dog animal = (Dog) pet;
int days = this.dogSpace.remove(pet);
double weight = animal.getDogWeight();
if(weight < 20) {
fee = 24.00;
if(animal.getGrooming()) {
groomingfee = 19.95;
}
} else if (weight > 20 && weight < 30) {
fee = 29.00;
if(animal.getGrooming()) {
groomingfee = 24.95;
}
} else {
fee = 34.00;
if(animal.getGrooming()) {
groomingfee = 29.95;
}
}
System.out.println("Fee Schedule:\n Boarding Fee: " + (fee*days) + "\nGrooming Fee: " + groomingfee);
animal.amountDue = (fee * days) + groomingfee;
return animal.amountDue;
}
else {
int days = this.catSpace.remove(pet);
fee = 18.00;
pet.amountDue = (fee * days);
return pet.amountDue;
}
}
public Pet getPet(Pet pet) { // Not sure why we need this.
return pet;
}
public Pet createPet(String name, int age, String type) {
switch(type) {
case "Dog":
return new Dog(name, age);
case "Cat":
return new Pet(name, age, "Cat"); // I have implemented the dog class, not the cat.
default:
throw new Error("Only Dogs and Cats can stay at this facility.");
}
}
/**
* Asks the user to fill in all of the attributes of a pet. Saves them directly to the object it was called on.
* #param pet - The pet you wish to update information on.
*/
public void updatePet(Pet pet) {
Scanner in = new Scanner(System.in);
System.out.println("What is the pets new name?");
pet.setPetName(in.next());
System.out.println("What is the pets age?");
pet.setPetAge(in.nextInt());
System.out.println("What type of animal is your pet?");
pet.setPetType(in.next());
in.close();
}
public String getPetName() {
return this.petName;
}
public int getPetAge() {
return this.petAge;
}
public String getPetType() {
return this.petType;
}
public void setPetName(String name) {
this.petName = name;
}
public void setPetAge(int age) {
this.petAge = age;
}
public void setPetType(String type) {
switch(type) { // while a switch is extra here, it will make it easier to add other pets.
case "Dog":
this.petType = type;
break;
case "Cat":
this.petType = type;
break;
}
}
public void setDaysStay(int days) {
this.daysStay = days;
}
}
public class Dog extends Pet {
public int dogSpaceNbr;
private double dogWeight;
private boolean grooming;
public Dog(String name, int age) { // automatically declares a pet of type Dog
super(name, age, "Dog"); // super is used to call the parent classes constructor
}
public double getDogWeight() {
return this.dogWeight;
}
public boolean getGrooming() {
return this.grooming;
}
public void setDogWeight(double weight) {
this.dogWeight = (double) weight; // casting a double here might be redundant, but it helps us to be sure
} // we don't get at type error
public void setGrooming(boolean value) {
this.grooming = value;
}
}
public class Cat extends Pet {
private int catSpaceNbr; // The number space the cat is in.
public Cat(String name, int age) { // automatically declares a pet of type Cat
super(name, age, "Cat"); // Calls the constructor of the parent class
}
public int getCatSpace() {
return this.catSpaceNbr;
}
public void setCatSpace(int number) {
this.catSpaceNbr = number;
}
}type here
I haven't tried much to fix the issue besides look up videos and now reach out for help just not sure what to do.
In the Package Exporer or Navigator tab (right hand panel) right-click on the class that contains public static void main and choose Run as >> Java application.
When you have done that successfully you can run with the run button.

Changing fields of class in java

So, I'm still learning java and coding so the resolution may be obvious but I just can't see it.
I'm writing a code about stars and constelations for uni assignment.
package com.company;
import java.util.*;
public class Main {
static public class Constellation {
public List<Star> constellation;
public String nameOfConstellation;
public Constellation(List<Star> constellation, String nameOfConstellation) {
this.constellation = constellation;
this.nameOfConstellation = nameOfConstellation;
}
public List<Star> getConstellation() {
return constellation;
}
}
static public class Star {
// private String categoryName;
private Constellation constellation;
private String nameOfConstelation;
public String getCategoryName() {
int index = constellation.getConstellation().indexOf(this);
String categoryName;
return categoryName = GreekLetter.values[index] + " " + this.constellation.nameOfConstellation;
}
public void deleteStar(Star x) {
this.constellation.constellation.remove(x);
}
}
public enum GreekLetter {
alfa,
beta,
gamma,
delta,
epsilon,
dzeta,
eta;
static public final GreekLetter[] values = values();
}
public static void main(String[] args)
{
Star x = new Star();
List<Star> fishCon = new ArrayList<>();
Constellation Fish = new Constellation(fishCon, "Fish");
x.constellation=Fish;
fishCon.add(x);
x.getCategoryName();
Star y = new Star();
y.constellation=Fish;
fishCon.add(y);
y.getCategoryName();
x.deleteStar(x);
for (Star w : Fish.constellation)
{
System.out.println(w.getCategoryName());
}
}
}
My point is to Update field categoryName after deleting one star. categoryName value is set in order of adding another star. For example I have first star - the name will be Alfa + nameOfConstelation. Second star - Beta + nameOfConstelation. When I call method deleteStar() I want to update all categoyName of my stars in constelation. Calling methods in deleteStar() doesn't work probably due to add() in setCategoryName. I would really appreciate any hints!
Since this appears to be homework, I am not posting code in this answer but rather giving suggestions that can help you create your own workable code:
Create a class called Constellation that holds the Stars in an List<Star> starList = new ArrayList<>();
Give Constellation a public List<Star> getStarList() method
Give each Star a Constellation field to hold the Constellation that contains this Star
Give each Star a getCategoryName() method that gets the Constellation object, iterates through its starList using a for-loop until it finds the this Star, and then that returns the appropriate name based on the index of the Star in the list.
Thus, if a Star is removed from the starList, the category names of all the other Stars held by that Constellation will update automatically and dynamically
Also,
You can give Constellation a public void deleteStar(Star star) method where it removes the Star parameter from its starList
You can also give Star a public void deleteFromConstellation() method where it checks its Constellation field, constellation, and if not null, calls constellation.deleteStar(this); and then sets the constellation field to null
Get rid of the private String categoryName; field in Star. This should be a calculated field, meaning the public String getCategoryName() does not return a field, but a String based on code (as described above).
It first checks that Star's constellation field is not null
It then gets the index of the Star in the Constellation's starList (I have given my Constellation class a public int getIndexOfStar(Star star) method.
It then uses this, the GreekLetter class, and the constellation.getName() method to create a String to return
Done.
Since you've figured this out, this is another way to code it:
public class SkyMain {
public static void main(String[] args) {
Constellation fish = new Constellation("Fish");
Star x = new Star();
Star y = new Star();
fish.addStar(x);
fish.addStar(y);
System.out.println("before removing x");
System.out.println("x category name: " + x.getCategoryName());
System.out.println("y category name: " + y.getCategoryName());
System.out.println("fish constellation: " + fish);
fish.removeStar(x);
System.out.println();
System.out.println("after removing x");
System.out.println("x category name: " + x.getCategoryName());
System.out.println("y category name: " + y.getCategoryName());
System.out.println("fish constellation: " + fish);
}
}
public class Star {
private Constellation constellation;
public void setConstellation(Constellation constellation) {
this.constellation = constellation;
}
public void removeFromConstellation() {
if (constellation != null) {
constellation.removeStar(this);
}
}
public String getCategoryName() {
if (constellation != null) {
int index = constellation.getIndexOfStar(this);
return GreekLetter.getGreekLetter(index).getName() + " " + constellation.getName();
} else {
return "";
}
}
#Override
public String toString() {
return getCategoryName();
}
}
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Constellation implements Iterable<Star> {
private String name;
private List<Star> starList = new ArrayList<>();
public Constellation(String name) {
this.name = name;
}
public String getName() {
return name;
}
public List<Star> getStarList() {
return starList;
}
public void addStar(Star star) {
starList.add(star);
star.setConstellation(this);
}
public void removeStar(Star star) {
if (starList.contains(star)) {
starList.remove(star);
star.setConstellation(null);
}
}
public int getIndexOfStar(Star star) {
return starList.indexOf(star);
}
#Override
public Iterator<Star> iterator() {
return starList.iterator();
}
#Override
public String toString() {
return "Constellation [name=" + name + ", starList=" + starList + "]";
}
}
public enum GreekLetter
{
ALPHA("alpha", 0),
BETA("beta", 1),
GAMMA("gamma", 2),
DELTA("delta", 3),
EPSILON("epsilon", 4),
ZETA("zeta", 5),
ETA("eta", 6);
private String name;
private int index;
private GreekLetter(String name, int index) {
this.name = name;
this.index = index;
}
public String getName() {
return name;
}
public int getIndex() {
return index;
}
public static GreekLetter getGreekLetter(int index) {
if (index < 0 || index > values().length) {
throw new IllegalArgumentException("for index " + index);
} else {
return values()[index];
}
}
}

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;

Trying to use 2 objects in Java

My goal is to have 2 different objects fight each other, and show the results. My problem is I cant figure out how to set the attack and health properly so that it actually updates the way it is supposted to.
import java.util.Random;
import java.util.Scanner;
/**
*
* #author Brenton
*/
public class Fighter {
private String name;
private int attack;
private int level = 1;
private int health = 50;
private boolean isAlive = true;
private Fighter fighterTwo;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getAttack() {
Random generator = new Random();
attack = generator.nextInt(10) * level + 1;
return attack;
}
public void setAttack(int attack) {
this.attack = attack;
}
public int getLevel() {
if(level >= 60)
{
level = 60;
}
return this.level;
}
public void setLevel(int level) {
this.level = level;
}
public int getHealth() {
if(this.health <= 0)
{
this.health = 0;
}
return this.health;
}
public void setHealth(int health) {
this.health = health;
}
public boolean isAlive() {
if(this.health <= 0)
{
this.isAlive = false;
}
return this.isAlive;
}
public static String getWelcome() {
String welcome = "Hello and welcome to FightClub, do you wish to fight, yes or no? ";
return welcome;
}
public String getPunch(Fighter fighterTwo) {
this.fighterTwo = fighterTwo;
String hit = "You choose to punch the other fighter and dealt " + getAttack() + " damage, your opponent now has " + this.decreaseHitPoints(fighterTwo) + " health remaining";
return hit;
}
public int decreaseHitPoints(Fighter fighterTwo) {
this.fighterTwo = fighterTwo;
int health = fighterTwo.getHealth();
int attack = getAttack();
health = health - attack;
return health;
}
public static String invalidInput() {
String invalid = "I am sorry that is not a valid input option ";
return invalid;
}
public void getWinner(Fighter fighterTwo) {
this.fighterTwo = fighterTwo;
if(this.isAlive() == false && fighterTwo.isAlive() == false)
{
System.out.println("Both fighters have fallen heroically");
}
else if(this.isAlive() == true && fighterTwo.isAlive() == false)
{
System.out.println(this.getName() + " is victorious! ");
}
else if(this.isAlive() == false && fighterTwo.isAlive() == true)
{
System.out.println(fighterTwo + " is victorious! ");
}
else
{
System.out.println("ERROR ERROR ERROR");
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Fighter a = new Warrior();
Fighter b = new Dragon();
System.out.print(getWelcome());
while(in.hasNextLine())
{
switch(in.nextLine())
{
case "no":
System.out.println("Wow, you are not even gonna try, you have lost!");
break;
case "yes":
System.out.println("Let the fight begin! ");
while(a.isAlive() && b.isAlive())
{
System.out.println("Do you want to punch, kick, or headbutt the other fighter? ");
switch(in.nextLine())
{
case "punch":
System.out.println(a.getPunch(b));
break;
/*case "kick":
System.out.println(a.getKick(b));
break;
case "headbutt":
System.out.println(a.getHeadbutt(b));
break;*/
default :
System.out.println(invalidInput());
break;
}
}
default:
System.out.println(invalidInput());
break;
}//end of first switch statement
}//end of first while loop
}//end of main
}
You're calculating the attack correctly. You're just not updating the state of the other fighter.
In your main() method you launch the attack with
System.out.println(a.getPunch(b));
That's just fine. a throws a Punch at b, then you print out the hit points returned from getPunch(). So let's dig deeper into getPunch() to try to find the problem.
In getPunch() you end up invoking
this.decreaseHitPoints(fighterTwo)
while constructing the return String. This seems like the right approach, so is there a problem in decreaseHitPoints()?
public int decreaseHitPoints(Fighter fighterTwo) {
this.fighterTwo = fighterTwo;
int health = fighterTwo.getHealth();
int attack = getAttack();
health = health - attack;
return health;
}
You assign the fighterTwo argument to your fighterTwo field. Not sure why, but that's not wrong per se. Then you get his health into a local variable called health. Then you get the attack into a local variable called attack. Then you subtract attack from health, and then return the calculated value. But you never update the health value on fighterTwo! So you just need one more line in your program: right before your return statement, insert
fighterTwo.setHealth(health);

How to sum the number of instances of an object in Java?

Right now I'm working on a basic java program that takes a few parameters into a constructor for a cup of coffee. That is easy enough but I'm having trouble creating a method for summing the number of coffee cups I've created.
So far this is the UseCoffee class I've created:
public class UsesCoffee{
public static void main(String args[]) {
System.out.println("cups created: " + Coffee.totalCups());
Coffee cup1 = new Coffee(350, "mint", true);
System.out.println("cup1: " + cup1);
Coffee cup2 = new Coffee(500, "mocha", false);
System.out.println("cups created: " + Coffee.totalCups());
System.out.println("cup2: " + cup2);
Coffee cup3 = new Coffee(350, "no flavour used", false);
cup3.doubleSize();
System.out.println("cup3: " + cup3);
Coffee cup4 = new Coffee(-10, "mocha", false);
System.out.println("cup4: " + cup4);
System.out.println("cups created: " + Coffee.totalCups());
if (Coffee.bigger(cup3,cup2))
System.out.println("cup3 is bigger than cup2");
if (Coffee.bigger(cup1,cup2))
System.out.println("cup1 is bigger than cup3");
if (Coffee.bigger(cup1,cup1))
System.out.println("cup1 is bigger than itself");
} // end main
} // end UsesCoffee
And this is the Coffee Class I've created:
public class Coffee {
private int coffeeVol;
private String coffeeFlav;
private boolean yesCream;
public Coffee(int volume, String flavour, boolean cream) {
this.coffeeFlav = flavour;
this.coffeeVol = volume;
this.yesCream = cream;
if (volume < 0) {
System.out.println("error: negative size. Defaultsize of 250 ml used");
coffeeVol = 250;
}
}
public String toString() {
return coffeeVol +"ml, " + coffeeFlav + ", " + yesCream;
} // end toString
public static int totalCups() {
//THIS IS WHERE I'M HAVING TROUBLE
}
public int doubleSize() {
coffeeVol = coffeeVol*2;
return coffeeVol;
}
}
Is there a way to sum the number of coffee cups? I'm truly lost in this respect, and any help is appreciated!
You could add a static variable to your Coffee class and increment it in your constructor.
Something like that:
public class Coffee {
private static int numberOfCups = 0;
private int coffeeVol;
private String coffeeFlav;
private boolean yesCream;
public Coffee(int volume, String flavour, boolean cream) {
this.coffeeFlav = flavour;
this.coffeeVol = volume;
this.yesCream = cream;
if (volume < 0) {
System.out.println("error: negative size. Defaultsize of 250 ml used");
coffeeVol = 250;
}
numberOfCups++;
}
public String toString() {
return coffeeVol +"ml, " + coffeeFlav + ", " + yesCream;
} // end toString
public static int totalCups() {
return numberOfCups;
}
public int doubleSize() {
coffeeVol = coffeeVol*2;
return coffeeVol;
}
public static boolean bigger(Coffee cup1, Coffee cup2) {
if (cup1.coffeeVol > cup2.coffeeVol) {
return true;
}
return false;
}
}
What you want to do is create a static field and increment it every time the constructor is called.
public class Coffee {
private static int totalCups;
// rest of the code ...
public Coffee(int volume, String flavour, boolean cream) {
totalCups++;
// rest of the code...
}
public static int getTotalCups() {
return totalCups;
}
}
// rest of the code ...
You want to make the field and method static because it will be shared by all instances of Coffee. You want to make totalCups a private field because of data encapsulation (you do not want to allow someone to change the total number of cups, which can only be modified logically via the constructor) and then retrieve it with a public getter method (which allows you to run additional data validation)
You might want to use something called an initialization block, and a static integer field to hold the current number of instances of your class. This is the best way of doing what you want, in my opinion.
public class Coffee
{
// Hold the number of instances.
private static int instances;
// This snippet of code will run whenever one of the //
// constructors below is called. All subclasses will //
// automatically inherit this too, by the way. //
{
instances++;
}
// first constructor
public Coffee() {}
// second constructor
public Coffee(int Foo) {}
// third constructor
public Coffee(double Bar) {}
// return the number of instances you have.
public static int totalCups()
{
return instances;
}
}
If you want to count the #/cups ... and you also want to compare each of the cups with each other ("which cup is largest") ... then you really ought to consider using a Collection.
EXAMPLE:
public class UsesCoffee{
public static void main(String args[]) {
ArrayList<Coffee> cups = new ArrayList<Coffee>();
System.out.println("cups created: " + cups.size());
cups.add(new Coffee(350, "mint", true));
cups.add(new Coffee(500, "mocha", false));
System.out.println("cups created: " + cups.size());
Coffee biggestCup = cups.get(0);
for (Coffee cup : cups) {
if (cup.coffeeVol > biggestCup.coffeeVol)
biggestCup = cup;
}
System.out.println("biggest cup is " + biggestCup.coffeeVol);
}
}

Categories

Resources