Reputation: 11
I am new to java/programming and I thought a good way to learn was making a simple text RPG game. Im on a class file where you can hire workers to mine ore for you. Basically, I take 2000 gold from the user, and randomize a number between 1-5 10 times and they get ore based on the number 10 times. (e.g, 1 is copper, 4 is gold)
this is what I have so far, when i run it it takes my gold but only gives me 1 ore when it really should give me 10, any help? edit: sorry forgot to mention i had int x = 0;at the top
if ((input.input.equalsIgnoreCase("a")) && inventory.goldCoins >= 2000) {
System.out.println("You have hired Sanchez for $2000!");
inventory.goldCoins -= 2000;
do {
int workerOre = (int )(Math.random() * 5 + 1);
if (workerOre == 1) {
inventory.addInventory("Copper Ore");
menu.start();
} else if (workerOre == 2) {
inventory.addInventory("Iron Ore");
menu.start();
} else if (workerOre == 3) {
inventory.addInventory("Steel Ore");
menu.start();
} else if (workerOre == 4) {
inventory.addInventory("Gold Ore");
menu.start();
} else if (workerOre == 5) {
inventory.addInventory("Copper Ore");
}
x++;
} while (x < 10);
System.out.println("Sanchez has finished his shift and the ore has been added to your inventory!");
} else if ((input.input.equalsIgnoreCase("a")) && inventory.goldCoins < 2000) {
System.out.println("You do not have enough money!");
worker();
}
Upvotes: 0
Views: 143
Reputation: 300
The reason could be that you never initialized x, so it is just equal to some garbage value. Try adding int x = 0
before your do-while loop.
I also noticed that you are calling menu.start()
after adding the Ore to your inventory, is there a chance that your program never gets back into the loop?
You will need to use a break
to jump out of the switch statement after it has identified the case, secondly you can add a default
to the end of the switch that will be used if there is ever a time that case 1 through case 4 are not satisfied. Ex:
switch(ore)
{
case 1: inventory.addInventory("Copper Ore");
break;
case 2: inventory.addInventory("Iron Ore");
break;
case 3: inventory.addInventory("Steel Ore");
break;
case 4: inventory.addInventory("Gold Ore");
break;
default: inventory.addInventory("Copper Ore");
}
Upvotes: 1
Reputation:
try something like:
for (int i = 0; i < 10; i++) {
mineOre();
}
public void mineOre() {
int ore = (int) Math.random() * 5 + 1;
switch (ore) {
case 1: inventory.addInventory("Copper Ore");
case 2: inventory.addInventory("Iron Ore");
case 3: inventory.addInventory("Steel Ore");
case 4: inventory.addInventory("Gold Ore");
case 5: inventory.addInventory("Copper Ore");
}
menu.start();
}
Upvotes: 0
Reputation: 4065
It looks like you never initialize x
.
Just add int x = 0
before you start the do...while
.
Upvotes: 0