gpt4 book ai didi

java - 正确使用构造函数来更改 int 值?

转载 作者:行者123 更新时间:2023-11-30 07:55:49 25 4
gpt4 key购买 nike

我有两个类。 1.主炮和2.枪。

枪:

public class Gun {
private int ammoAmount = 15;
public int getAmmoAmount() { //I believe this allows me to see the value of ammoAmount and use it in Main class.
return ammoAmount; // Returns the value of ammoAmount to getAmmoAmount?
}
public Gun(int ammoUsage) { //this is the constructor right?
ammoAmount = ammoAmount - ammoUsage; //Method that makes ammoAmount decrease by ammoUsage.
}
public void newAmmoAmount() {
System.out.println("You have " + ammoAmount + " bullet(s) left."); // output of how much bullet is left.
}
}

主要:

import java.util.Random;
public class Main {

public static void main(String[] args) {

Random rand = new Random();
Gun fire1 = new Gun(0); // I need this to create an objective?
fire1.newAmmoAmount(); // I need this for code below?
int clip = fire1.getAmmoAmount(); // I need this to set clip for while loop?
do { //starts loop
int x = 5; //max # random can go to.
int y = rand.nextInt(x); //Makes random integer from 0 to 5 for variable y.
Gun fire = new Gun(y); //This is the objective that uses the constructor?
System.out.println("You shot " + y + " bullet(s)."); //Print's out shots from random value y.
fire.newAmmoAmount(); //uses method in Gun class?
} while( clip > 0); //loops method till clip is less than 0.
}
}

我尝试运行该程序,但它一直循环并且永远不会结束。 ammoAmount 的值不保存在 Gun 类中。如何才能更改不同类的 int 值?

我最近也有一个问题。我尝试按照他的说法使用构造函数。

How do I call a class into a class from main? and keep the output values?

但正如你所看到的,我并不是很成功。这只是我试图达到的一个更大概念的一个较小概念。所以基本上,我做对了构造函数吗?解决这个问题的方法是什么?

我在源代码中添加了一些注释,以向您展示我可能遇到的其他问题以及我是否也做了正确的事情。

最佳答案

你的“Gun”对象是不可变的 - 没有任何东西可以改变该对象的状态。此类类型有很多用途,但不太可能是您想要的。

听起来您想要“枪”的实例“开火”,因此“枪”实例中重命名子弹的数量会减少。当然,创建新的“枪”对象不会改变第一个对象中的子弹数量。

public class Gun {
...
public fire(int ammoUsage) {
ammoAmount = ammoAmount - ammoUsage; // TODO: add check for less than 0
}
}

使用此更新类,您可以开火直到没有子弹为止:

   int maxBulletsPerRound = 5; 
Gun gun = new Gun(0); // fully loaded
int clip;
do {
int numberOfBullets = rand.nextInt(maxBulletsPerRound);
gun.fire(numberOfBullets);
System.out.println("You shot " + numberOfBullets + " bullet(s).");
gun.newAmmoAmount(); //uses method in Gun class?
clip = gun.getAmmoAmount(); // check how many bullets left
} while( clip > 0);

请注意,最好只使用 while(gun.getAmmoAmount() > 0)

关于java - 正确使用构造函数来更改 int 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32688080/

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