使用整数为每个方法调用增加一个字符串数组
using ints to increment through a string array for each method invocation
在 class 中,我这里有一个方法应该为每次调用添加到 int mWeight
,然后每调用三次,遍历 mSize
数组.在我调用 getter 的主要方法中,我没有在数组中获得任何更高的字符串值。
这里是相关的 class 变量和 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;
}
您可以为狗吃的饭数维护一个变量。
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;
}
}
在 class 中,我这里有一个方法应该为每次调用添加到 int mWeight
,然后每调用三次,遍历 mSize
数组.在我调用 getter 的主要方法中,我没有在数组中获得任何更高的字符串值。
这里是相关的 class 变量和 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;
}
您可以为狗吃的饭数维护一个变量。
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;
}
}