简体   繁体   中英

Complex loop help. Java

This program is a simple card game and I am hung up on one complex loop. This "fire" card needs to check its 2 neighbor gameboard slots to see if it is occupied by another card, and if so, if it is a card that it can affect. With this loop it either needs to run once successfully, or twice unsuccessfully. I thought I had it figured with the code below, but when it runs the loop unsuccessfully, the program crashes with no errors. Let me know what you think, Thanks.

This code is just the method, the main is not included.

public static void fireAction(String slotSelection)
{
    switch (slotSelection)
    {
        case "A1":
            {
                boolean x = true;
                boolean y = true;
                boolean end = false;
                while ((y == true && x == true) || (end == false))
                {   
                    int burn = roll.nextInt(2);
                    switch (burn)
                    {
                        case (0):
                            if ((newBoard.getSlotA2() == "fire") | (newBoard.getSlotA2() == "wind")){
                                newBoard.setSlotA2("BURNED");
                                end = true;}
                            else
                                x = false;
                            break;
                        case (1):
                            if ((newBoard.getSlotB1() == "fire") | (newBoard.getSlotB1() == "wind")){
                                newBoard.setSlotB1("BURNED");
                                end = true;}
                            else
                                y = false;
                            break;
                    }//end switch
                }//end while
            }//end case A1
            break;

Try to use && instead of || :

    while ((y == true && x == true) && (end == false))

and also maybe you should use || instead of | in the following code:

 if ((newBoard.getSlotA2() == "fire") | (newBoard.getSlotA2() == "wind"))

You could use a for loop instead of while to prevent it from looping infinitely. Also, setting end to true will not necessarily end the loop, since x and y could still be true. A better condition would be:

    while((x && y) && (!end)){

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM