gpt4 book ai didi

Java基本对象程序

转载 作者:行者123 更新时间:2023-12-01 07:23:30 24 4
gpt4 key购买 nike

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

谢谢:)

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

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

输出:

现在你瓶子里的水量是:0

最佳答案

您添加并饮用相同的量。添加后您必须生成一个新的随机数,如下所示:

    int rand = (int)(Math.random()*100);
waterbottle.addwater(rand);
rand = (int)(Math.random()*100);
waterbottle.drinkwater(rand);

关于Java基本对象程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30145884/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com