Java do-while循环中正负数计数器统计结果异常问题
问题描述
使用do-while循环实现正负数输入统计功能,规则为输入0时终止程序,分别统计输入的正数、负数个数,0不计入统计。测试时依次输入4个正数、3个负数后输入0,预期输出正数数量4、负数数量3,实际运行输出正数3个、负数3个,尝试将后置自增运算符替换为前置自增运算符后问题仍存在。
实际运行输入输出记录
Enter an integer, the input end if it is 0: 4 Enter an integer, the input end if it is 0: 3 Enter an integer, the input end if it is 0: 2 Enter an integer, the input end if it is 0: 1 Enter an integer, the input end if it is 0: -4 Enter an integer, the input end if it is 0: -3 Enter an integer, the input end if it is 0: -2 Enter an integer, the input end if it is 0: 0 num of postives 3 and num of negatives 3 <----- output wrong
原始问题代码
import java.util.Scanner; public class App { public static void main(String[] args) throws Exception { /** * my pesducode * enter an integer, input ends if 0: * while input != 0 * if input > 0 * postives = postiveCount++ * else * negatives = negativeCount++ * total+= input * end loop * totalNumsEnter = postive + negatives * avg = total/ totalNumsEnter */ Scanner input = new Scanner(System.in); int num = 0; int postiveCount = 0; int postives = 0; int negatives = 0; int negativeCount = 0; do{ System.out.print("Enter an integer, the input end if it is 0: "); num = input.nextInt(); if(num > 0){ postives = postiveCount++; } else{ negatives = negativeCount++; } }while( num != 0); System.out.printf("num of postives %d and num of negatives %d", postives,negatives); input.close(); } }
问题原因
代码存在两处核心逻辑错误:
- 冗余定义重复计数变量:同时声明了
postiveCount/postives、negativeCount/negatives两组功能完全一致的计数变量,多余的跨变量赋值操作直接导致计数传递错误。 - 计数逻辑与边界判断缺失:
- 执行
postives = postiveCount++时,后置自增运算符会先返回postiveCount的当前值完成赋值,再对postiveCount做自增。最后一次输入正数时,postiveCount自增后的值为4,但赋值给postives的是自增前的3,这是正数统计少1的直接原因。就算替换为前置自增,双变量赋值的逻辑依然会存在计数不同步的问题。 - do-while循环是先执行循环体再判断终止条件,输入0时会先进入循环体走到else分支,若不做过滤会错误给负数计数加1,本次测试中负数结果恰好正确属于赋值逻辑掩盖下的巧合。
- 执行
修复后代码
import java.util.Scanner; public class App { public static void main(String[] args) throws Exception { Scanner input = new Scanner(System.in); int num; int positives = 0; int negatives = 0; do{ System.out.print("Enter an integer, the input end if it is 0: "); num = input.nextInt(); // 输入0直接跳过计数 if(num == 0){ break; } if(num > 0){ positives++; } else { negatives++; } }while( num != 0); System.out.printf("num of positives %d and num of negatives %d", positives,negatives); input.close(); } }
修改点说明
- 删除冗余的
postiveCount、negativeCount变量,直接用输出对应的positives、negatives作为计数器,避免多变量赋值带来的数值不同步问题 - 读取输入后增加0值判断,遇到终止符直接跳过计数逻辑,避免边界值污染统计结果
- 修正原代码中
postives的拼写错误为标准命名positives
内容的提问来源于stack exchange,提问作者user18904944
相关产品推荐
相关产品推荐

