我一直盯着这看似几个小时,我不能为我的生活弄清楚为什么运行时的输出卡在一个循环中,就像这样(是的,我现在只是纠正拼写估计):
你未来的孩子将成长为4英尺10英寸。 你未来的孩子将成长为4英尺10英寸。 你未来的孩子将成长为4英尺10英寸。 你未来的孩子将成长为4英尺10英寸。 你未来的孩子将成长为4英尺10英寸。 你未来的孩子将成长为4英尺10英寸。 你未来的孩子将成长为4英尺10英寸。 你未来的孩子将成长为4英尺10英寸。 你未来的孩子将成长为4英尺10英寸。 你未来的孩子将成长为4英尺10英寸。 你未来的孩子将成长为4英尺10英寸。 你未来的孩子将成长为4英尺10英寸。 你未来的孩子将成长为4英尺10英寸。 你未来的孩子将成长为4英尺10英寸。 你未来的孩子将成长为4英尺10英寸
每次我编写循环时都会发生这种情况。
//允许使用键盘 扫描仪keyboardInput = new Scanner(System.in);
//Allows user to input numbers System.out.println("Enter the gender of your future child. Use 1 for Female and 0 for Male: "); int Gender = keyboardInput.nextInt(); System.out.println("Enter the height in feet, then in inches of the mom: "); int MomHeight = keyboardInput.nextInt(); System.out.println("Enter the height in feet, then the height in inches of the dad: "); int DadHeight = keyboardInput.nextInt(); int female; int male; int HeightFeet; int HeightInches; DecimalFormat feet = new DecimalFormat("#0"); DecimalFormat inches = new DecimalFormat("#0"); //Loop statements while (Gender == 0) { male = (MomHeight * 13 / 12 + DadHeight) / 2; HeightFeet = male / 12; HeightInches = male % 12; System.out.print("Your future child is estimated to grow to " + feet.format(HeightFeet)); System.out.print(" feet and " + inches.format(HeightInches)); System.out.print(" inches."); System.out.println(""); } while (Gender == 1) { female = (DadHeight * 12 /13 + MomHeight) /2; HeightFeet = female / 12; HeightInches= female % 12; System.out.print("Your future child is estmated to grow to " + feet.format(HeightFeet)); System.out.print(" feet and " + inches.format(HeightInches)); System.out.print(" inches."); System.out.println(""); } } }
答案 0 :(得分:3)
在循环中,永远不会修改Gender
。所以你永远循环。
现在,我认为你不需要while
声明
if else if
声明会更好,因为您不会从用户那里获取新的输入进行循环,但您希望根据特定条件(男性或女性)应用处理。
顺便说一下,您应该将变量命名为gender
而不是Gender
来尊重Java命名约定:
if (gender == 0){
...
}
else if (gender == 1){
...
}
如果要多次重复所有处理,可以使用循环覆盖所有处理:
boolean again = false;
do{
if (gender == 0){
...
}
else if (gender == 1){
...
}
...
again = keyboardInput.nextBoolean();
} while (again);
答案 1 :(得分:0)
为了退出循环,您需要在循环执行完所需次数后变为false。
同样在上面的代码中,您似乎在要执行的语句之间做出选择,而不是运行传统的循环。考虑使用“if”语句
while (Gender == 0){
//Do this
}
while (Gender == 1){
//Do this instead
}
如果您希望在打印输出语句“X”次之后退出循环,您宁愿将条件基于计数变量。
因此,选择是基于性别变量,打印语句基于计数变量。
//Assume print is to be done 2 times
int count = 1;
if(Gender == 0){
//Female selection
while( count < 3 ){
// Execute female code
count++;
}
else if(Gender == 1){
//Male selection
while( count < 3 ){
// Execute male code
count++;
}