[英]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. 我正在为我的Java类开发一个程序,该程序需要计算一对夫妇要拥有每种性别需要多少个孩子,并假设该孩子有50/50的机会是男性。 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.
然后,该程序需要跟踪在一次T量试验中,每个性别有2个孩子经历了多少次,3个孩子,4个孩子以及最后有5个或更多孩子经历了多少次。 I tackled this by nesting a while loop within a for loop that runs T amount of times.
我通过在运行T次的for循环中嵌套一个while循环来解决此问题。 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.
我的问题是,尽管我的for循环运行了T次,但我的while循环会吐出3个孩子,然后在其余的for循环中不更新。 Any advice as to how to get the while loop to update properly?
关于如何使while循环正确更新的任何建议? 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:
因此,您的while循环周围的代码应为:
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. 但是,在while循环之后,您需要计算此运行适用的家庭人数:2个孩子,3个孩子,4个孩子,5个以上孩子,并增加适当的计数器。
switch(boys + girls) {
case 2:
twoKids++;
break;
case 3:
threeKids++;
break;
case 4:
fourKids++;
break;
default:
fivePlusKids++;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.