java - properly using constructors to change int value? -
i have 2 classes. 1. main , 2. gun.
gun:
public class gun { private int ammoamount = 15; public int getammoamount() { //i believe allows me see value of ammoamount , use in main class. return ammoamount; // returns value of ammoamount getammoamount? } public gun(int ammousage) { //this constructor right? ammoamount = ammoamount - ammousage; //method makes ammoamount decrease ammousage. } public void newammoamount() { system.out.println("you have " + ammoamount + " bullet(s) left."); // output of how bullet left. } }
main:
import java.util.random; public class main { public static void main(string[] args) { random rand = new random(); gun fire1 = new gun(0); // need create objective? fire1.newammoamount(); // need code below? int clip = fire1.getammoamount(); // need set clip while loop? { //starts loop int x = 5; //max # random can go to. int y = rand.nextint(x); //makes random integer 0 5 variable y. gun fire = new gun(y); //this objective uses constructor? system.out.println("you shot " + y + " bullet(s)."); //print's out shots random value y. fire.newammoamount(); //uses method in gun class? } while( clip > 0); //loops method till clip less 0. } }
i try running program keeps on looping , never ends. value ammoamount not saved in gun class. how make can change int value different class?
i had recent question well. tried using constructors stated.
how call class class main? , keep output values?
but can see i'm not successful. smaller concept of bigger 1 trying to. basically, did constructors right? , fix this?
i added comments source code show other questions might possibly have , if did right well.
your "gun" object immutable - there nothing can change state of object. such types have lot of usage, unlikely want.
it sounds want instance of "gun" "fire" , result number of renaming bullets in instance of "gun" decrease. creating new "gun" object not change number of bullets in first one.
public class gun { ... public fire(int ammousage) { ammoamount = ammoamount - ammousage; // todo: add check less 0 } }
with update class can fire
till no bullets left:
int maxbulletsperround = 5; gun gun = new gun(0); // loaded int clip; { 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);
note may better use while(gun.getammoamount() > 0)
.
Comments
Post a Comment