【问题标题】:using ints to increment through a string array for each method invocation对于每个方法调用,使用 int 通过字符串数组递增
【发布时间】:2015-02-11 07:43:05
【问题描述】:

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

这里是相关的类变量和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;
}

【问题讨论】:

  • 你没有忘记while 后面的花括号吗? dogSize 声明在哪里?
  • 当我看到“每 3 次调用它”时,我在想实例范围计数器和模运算符。
  • 已编辑。 dogGender 应该是 dogSize,在成员变量中声明。

标签: java arrays methods


【解决方案1】:

您可以为狗的用餐次数维护一个变量。

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; 
        }
}

【讨论】:

    猜你喜欢
    • 2020-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-25
    • 1970-01-01
    • 2023-02-07
    • 1970-01-01
    相关资源
    最近更新 更多