As others already wrote, Java is an Object Oriented Programming Language and you should take advantage of that.
A good way of ensuring that a value stays within a defined range is to implement a type where you can set an upper limit, a lower limit and a changeable value. A basic implementation could look like this:
public class RangedValue {
private final int lowerLimit;
private final int upperLimit;
private int value;
public RangedValue(int lowerLimit, int upperLimit, int value) {
if (lowerLimit >= upperLimit) {
throw new IllegalArgumentException("The lowerLimit must be less " +
"than the upperLimit!");
}
this.lowerLimit = lowerLimit;
this.upperLimit = upperLimit;
this.value = RangedValue.ensureRange(value, upperLimit, lowerLimit);
}
/**
* Helper method to ensure that a value stays within the defined range.
*
* @param value The value to be kept in the defined range
* @param upperLimit The upper limit of the range
* @param lowerLimit The lower limit of the range
* @return The value or the lowerLimit or the upperLimit
*/
private static int ensureRange(int value, int upperLimit, int lowerLimit) {
if (value > upperLimit) {
return upperLimit;
} else if (value < lowerLimit) {
return lowerLimit;
}
return value;
}
public int increaseValueBy(int value) {
int increased = this.value + value;
this.value = RangedValue.ensureRange(increased, upperLimit, lowerLimit);
return this.value;
}
public int reduceValueBy(int value) {
return increaseValueBy(-value);
}
public int setValue(int value) {
return RangedValue.ensureRange(value, upperLimit, lowerLimit);
}
public int getLowerLimit() {
return lowerLimit;
}
public int getUpperLimit() {
return upperLimit;
}
public int getValue() {
return value;
}
}
Then you could use this class for your existing code:
RangedValue food = new RangedValue(0, 50, 30);
RangedValue health = new RangedValue(0, 50, 30);
RangedValue happiness = new RangedValue(0, 50, 30);
System.out.println(" type cat name");
catName = input.nextLine();
You could define the cat in a separate class as well, of course, but that's up to you.
VirtualCatclass with those three properties. Java is an object-oriented language. Use that to your benefit. You could start here.