简体   繁体   中英

Is there a way to tie multiple if statements to one else statement?

I'm working on a program for Computer Science where I have to make a game of Yahtzee, and I was wondering about something - is there a way to have all of these if statements tie to a single else? It would be sort of like a switch statement where I can check if they're equal and if not, just use the one else to equate sameNum to maxSam. I can't use else ifs because the conditions are all separate from each other and I can't use a switch because I need to check for some things. It's also not allowed, for whatever reason.

This is my code. The variable 'sameNum' is for the streak amount of the same dice, and 'maxSame' is the highest streak so far. I'd like to lessen the amount of lines if possible, but if I need all the if statements it's alright.

I wanted to hold off on continuing the program until I found a better answer, but the rest of the if/elses would be something like:

if(curDice == d1 && iteration != 1) etc etc

    for(int i = 0; i < 5; i++)
    {
        switch(iteration)
        {
            case 0:
                curDice = d1;
            case 1:
                curDice = d2;
            case 2:
                curDice = d3;
            case 3:
                curDice = d4;
            case 4:
                curDice = d5;
        }
        if(curDice == d1 && iteration != 0)
        {
            sameNum++;
        }
        else
        {
            if(sameNum > maxSame)
            {
                maxSame = sameNum;
            }
        }
        /* keep doing this for the rest of the dice*/
        iteration++;
    }

Please don't take this the hard way, but your code tries to solve something easy in a very hard way.

First of all you should store your dice results in an array. that will make math operations on it SO much easier.

Since you mentioned its for CS your and you are iterating a fixed amount, it is probably fastest(not runtime but coding time wise) to just iterate that array 6 times and determine which number appeared most often.


dices = new int[5];

int biggestMatch = 0;
int matchingDice = 0;

for(i = 1; i <= 6; i++){
    int currentMatch = 0;
    for(int d : dices){
        if(i == d){
            currentMatch ++;
        }
    }
    if(currentMatch > biggestMatch){
        biggestMatch = currentMatch;
        matchingDice = i;
    }
}

matchingDice is now the number that you rolled the most and biggestMatch is how often.

You could also store the result in an array if you want to check for a street for example.

diceResults[0,1,2,0,0,1] where the index represents the dice value -1 (because arrays start at 0) and value in that field how often you rolled that dice.

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