使用int为每个方法调用递增一个字符串数组

时间:2015-02-11 07:43:06

标签: java arrays methods

在一个类中,我有一个方法,应该为每个调用添加到int mWeight,然后每三次调用它,移动mSize数组。在我调用getter的main方法中,我没有在数组中获得任何更高的字符串值。

以下是相关的类变量和getter。

// Amount of weight to gain after eating
    final float WEIGHT_GAIN = 0.25f;

 // Its weight in pounds
    float mWeight;

// Size, either "tiny", "small", "average", or "large"
    String mSize[] = {"tiny", "small", "average", "large"};

 int dogSize;

String getSize(){
    return mSize[dogSize];

该方法及其需要做的事情。

/*
 * feed
 *
 * Feeds the Dog.
 *
 * Side-effect: 1. The Dog gains weight, specifically WEIGHT_GAIN
 *              2. Every 3 meals, the Dog grows to a larger size, if
 *                 possible
 *                 i.e. "tiny" (3 meals later ->) "small" (3 meals later ->)
 *                 "average" (3 meals later ->) "large"
 *                 the Dog cannot exceed the "large" size or shrink smaller than
 *                 "tiny"
 * @return nothing
 */ 

void feed(){
    while(mWeight < mSize.length)
    mWeight ++;
    mWeight = mWeight * WEIGHT_GAIN; 
    dogSize += (int)mWeight/3;
    if (dogSize > mSize.length)
    dogSize = mSize.length;
}

1 个答案:

答案 0 :(得分:0)

你可以为狗吃的饭数维持一个变量。

final float WEIGHT_GAIN = 0.25f;
String mSize[] = {"tiny", "small", "average", "large"};
class Dog{
        int num_meals, mWeight, dogSize;
        public Dog(int weight){
            num_meals = 0;
            dogSize = 0;
            mWeight = weight;
        }
        public String getSize(){
            return mSize[dogSize];
        }
        void feed(){
            mWeight += mWeight * WEIGHT_GAIN;
            num_meals++;
            dogSize = num_meals/3 < mSize.length-1 ? num_meals/3 : mSize.length - 1; 
        }
}