实现ThreeWayLamp类switch方法时,如何处理数组索引越界与状态循环?
三路灯泡类(ThreeWayLamp)问题解决方案
核心解决思路
用取模运算处理循环切换逻辑,同时对负数参数做合法性校验,无需大幅修改原有核心结构,仅需优化switch方法的实现即可解决索引越界问题。
具体实现步骤
- 状态枚举化:将四种状态用数组或枚举类统一管理,避免硬编码判断,提升可维护性。
- 参数合法性校验:在
switch方法开头判断参数是否小于0,是则直接抛出IllegalArgumentException异常。 - 循环索引计算:用当前状态索引加上触发次数,再对状态总数取模,得到最终状态的索引——取模运算天然支持循环逻辑,比如状态总数为4时,5次触发等价于1次触发(
5 % 4 = 1),完美解决越界问题。 - 更新并输出状态:根据计算出的索引更新当前状态,然后打印最终状态。
代码示例(Java实现)
基础数组版本
public class ThreeWayLamp { private static final String[] STATES = {"Off", "LowLight", "MediumLight", "HighLight"}; private int currentStateIndex; public ThreeWayLamp() { // 初始状态为Off currentStateIndex = 0; } public void switchLamp(int times) { // 校验负数参数 if (times < 0) { throw new IllegalArgumentException("触发次数不能为负数"); } // 取模实现循环切换,避免索引越界 currentStateIndex = (currentStateIndex + times) % STATES.length; // 打印最终状态 System.out.println(STATES[currentStateIndex]); } public static void main(String[] args) { ThreeWayLamp lamp = new ThreeWayLamp(); lamp.switchLamp(5); // 输出 LowLight lamp.switchLamp(3); // 输出 Off lamp.switchLamp(-1); // 抛出异常 } }
规范枚举版本(推荐)
public enum LampState { OFF, LOW_LIGHT, MEDIUM_LIGHT, HIGH_LIGHT } public class ThreeWayLamp { private LampState currentState; public ThreeWayLamp() { currentState = LampState.OFF; } public void switchLamp(int times) { if (times < 0) { throw new IllegalArgumentException("触发次数不能为负数"); } LampState[] states = LampState.values(); // 计算新状态索引 int currentIndex = currentState.ordinal(); int newIndex = (currentIndex + times) % states.length; currentState = states[newIndex]; // 打印友好格式的状态名称 System.out.println(switch(currentState) { case LOW_LIGHT -> "LowLight"; case MEDIUM_LIGHT -> "MediumLight"; case HIGH_LIGHT -> "HighLight"; default -> "Off"; }); } }
结构修改建议
- 如果当前代码是用数组存储状态,无需修改核心结构,仅添加取模逻辑即可解决问题。
- 如果当前是用硬编码的多分支判断(比如嵌套if-else或switch-case),建议改成数组/枚举类的方式——不仅能解决越界问题,后续新增状态时只需修改数组/枚举,无需调整切换逻辑,代码更简洁易维护。
内容的提问来源于stack exchange,提问作者Roy
相关产品推荐
相关产品推荐

