简体   繁体   中英

Loops in simple Java program

I'm working on a program for my Java class which needs to calculate how many children a couple would need to have in order to have one of each sex, assuming its a 50/50 chance that the child will be a male. The program then needs to keep track of how many times it took 2 children to have one of each sex, how many times it took 3 children, 4 children, and finally 5 or more children in T amount of trials. I tackled this by nesting a while loop within a for loop that runs T amount of times. My problem is that, although my for loop is running T amount of times, my while loop will spit out, say, 3 children and then not update for the rest of the for loop. Any advice as to how to get the while loop to update properly? Thanks!

public class B
{
    public static void main(String[] args) 
    {
        int girls = 0;
        int boys = 0;
        System.out.print("Enter variable: ");
        int T = StdIn.readInt();

        for (int i = 0; i < T; i++)
        {
            while ((boys < 1) || (girls < 1))
            {
                if (Math.random() < 0.5)
                {
                    boys = boys + 1;
                }   
                else
                {
                    girls = girls + 1;
                }   
            }
        }
    }
}

You need to reset the boy and girl count each run. Therefore the code around your while loop should be:

boys = 0;
girls = 0;
while ((boys < 1) || (girls < 1))

But then after the while loop, you need to calculate which family size this run applies to: 2 kids, 3 kids, 4 kids, 5+ kids and increment the appropriate counter.

switch(boys + girls) {
    case 2:
        twoKids++;
    break;

    case 3:
        threeKids++;
    break;

    case 4:
        fourKids++;
    break;

    default:
        fivePlusKids++;
}

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