以下代碼:for循環復位建設投入
System.out.println("How many types of food do the gerbils eat?");
int F = keyboard.nextInt();
food = new food[F];
for
(int a = 0; a<F; a++){
System.out.println("Name of food number " + (a+1));
foodname = keyboard.next();
System.out.println("Max amount of food " + (a+1));
maximum = keyboard.nextInt();
food[a] = new food(foodname, maximum);
for (int n = 0; n<F; n++){
System.out.println(food[n]);
}
}
我得到以下輸出:
How many types of food do the gerbils eat?
2
Name of food number 1
p
Max amount of food 1
5
p 5
null
Name of food number 2
r
Max amount of food 2
5
r 5
r 5
正如你所看到的,每次循環重新開始的時間,對食物的新的輸入值名字和食物最大值被重置。爲什麼它這樣做,我如何解決它,以便它存儲我原來的食物1名稱和最大的輸入?
類食物:
public class food {
public static String foodname;
public static int maximum;
public food(String foodname, int maximum) {
this.foodname = foodname;
this.maximum = maximum;
}
public String getFood(){
return foodname;
}
public int getmaxamount(){
return maximum;
}
public String toString() {
return (this.getFood() + " " + this.getmaxamount());
}
}
什麼關鍵字static方法? –