# switch 我们希望编写一个函数,统计一个 `List` 列表中的数值分布,其中 1 是 small,2 是 middle, 3 是 big,3以上都是 huge 。列表中的数值全部都在 1 到 5之间,下列哪个程序会在对象的 small, middle, big, huge 四个字段 保存正确的统计结果? ## 答案 ```java public class Counter{ int small = 0; int middle = 0; int bug = 0; int huge = 0; //... getter methods public void read(List numbers){ for(var value: numbers){ switch(value){ case 1: small += 1; break; case 2: middle += 1; break; case 3: big += 1; break; default: huge +=1; } } } } ``` ## 答案 ### A ```java public class Counter{ int small = 0; int middle = 0; int bug = 0; int huge = 0; //... getter methods public void read(List numbers){ for(var value: numbers){ switch(value){ case 1: small += 1; case 2: middle += 1; case 3: big += 1; default: huge +=1; } } } } ``` ### B ```java public class Counter{ int small = 0; int middle = 0; int bug = 0; int huge = 0; //... getter methods public void read(List numbers){ for(var value: numbers){ switch(value){ case 1: small += 1; return small; case 2: middle += 1; return middle; case 3: big += 1; return big; default: huge +=1; return huge; } } } } ``` ### C ```java public class Counter{ int small = 0; int middle = 0; int bug = 0; int huge = 0; //... getter methods public void read(List numbers){ for(var value: numbers){ switch(value){ case 1: small += 1; return value; case 2: middle += 1; return value; case 3: big += 1; return value; default: huge +=1; return value; } } } } ``` ### D ```java public class Counter{ int small = 0; int middle = 0; int bug = 0; int huge = 0; //... getter methods public void read(List numbers){ for(var value: numbers){ switch(value){ case 1: small += 1; break; case 2: middle += 1; break; case 3: big += 1; break; default: huge +=1; } } } } ```