簡體   English   中英

循環if語句

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM