[英]Looping in if statement
我是java / programming的新手,我认为学习一个好方法是制作一个简单的RPG游戏。 我在课程文件中,您可以雇用工人为您开采矿石。 基本上,我从用户那里获得2000黄金,并在1-5 10次之间随机分配一个数字,然后根据该10次获得矿石。 (例如1是铜,4是金)
到目前为止,这就是我所拥有的,当我运行它时,它需要我的金,但是在真正应该给我10时,它只能给我1矿,有什么帮助吗? 编辑:抱歉忘了提到我有int x = 0;在顶部
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();
}
原因可能是您从未初始化过x,所以它刚好等于某个垃圾值。 尝试在do-while循环之前添加int x = 0
。
我还注意到,在将矿石添加到清单后,您正在调用menu.start()
,那么您的程序是否有可能永远不会回到循环中?
在确定案例之后,您需要使用break
来跳出switch语句,其次,您可以在switch的末尾添加一个default
,如果案例1到case 4曾经存在过,将使用default
不满意。 例如:
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");
}
看来您从未初始化x
。
在开始do...while
之前,只需添加int x = 0
。
尝试类似:
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.