Java基础对象程序

Jay*_*oob 0 java object

我不明白为什么它不给出随机数量.请解释.

谢谢 :)

我的代码(从教程中学到):

public class day5 {
    int totalwater = 0;

    public day5(){
        //default constructor
    }
    public day5(int wateramount){
        totalwater = wateramount;
    }
    // don't need static in Object. It will be used in other classes.
    public void addwater(int amount){
        totalwater = totalwater + amount;
    }
    public void drinkwater(int amount){
        totalwater = totalwater - amount;
    }
    public int getwater(){
        return totalwater;
        //because we are going to return an integer, public "int" and "return"
    }
}



public class day5obtest {
    public static void main(String[] args){
        day5 waterbottle = new day5(0);
        int rand = (int)(Math.random()*100);
        waterbottle.addwater(rand); 
        waterbottle.drinkwater(rand);
        System.out.println("The amount of water in your bottle now is: " + waterbottle.getwater());
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

现在瓶子里的水量是:0

Tam*_* G. 5

你添加和饮用相同的量.添加后您必须生成新的随机数量,如下所示:

    int rand = (int)(Math.random()*100);
    waterbottle.addwater(rand); 
    rand = (int)(Math.random()*100);
    waterbottle.drinkwater(rand);
Run Code Online (Sandbox Code Playgroud)