Java中能否在一个方法内编写多个switch case计算比赛三次得分?
Java射击比赛得分计算代码问题修复
基础疑问解答
Java完全支持在同一个方法内编写多个switch case,你遇到的运行错误和switch本身无关,是代码逻辑调用顺序、重载方法匹配错误导致的。
核心问题梳理
- 你写的switch分数换算逻辑全部放在**4参数的
setScore(int i, int test1, int test2, int test3)重载方法中,但主类实际调用的是3参数的setScore(int test1, int test2, int test3)**方法,该方法仅存储了原始靶号,从未触发switch换算,所以nl1/nl2/nl3始终是int类型的默认值0,汇总得分自然为0。 getC1()/getC2()/getC3()返回的是原始输入的靶号,没有经过分数转换,直接相加得到的就是靶号的总和,和你需要的换算后得分没有关系。- 构造方法、3参数
setScore方法在调用setEnd1()汇总得分时,nl1/nl2/nl3还没有被赋值,计算结果必然错误。 - 子类
Arrow1存在拼写错误,返回类型Panah应为Arrow,内部逻辑也存在冗余问题。
修正后的代码示例
Arrow类修正
class Arrow { // 存储原始靶号 private int test1; private int test2; private int test3; // 存储最终总得分 private int end1; // 无参构造 public Arrow() { } // 带参构造 public Arrow(int test1, int test2, int test3) { // 直接调用统一的设值方法完成赋值+计算 setScore(test1, test2, test3); } // 统一的分数设置方法:同时完成靶号存储、分数换算、总分计算 public void setScore(int test1, int test2, int test3) { this.test1 = test1; this.test2 = test2; this.test3 = test3; // 直接在该方法内完成三次射击的分数换算 int nl1 = switch (test1) { case 1 -> 100; case 2 -> 90; case 3 -> 80; case 4 -> 70; case 5 -> 60; case 6 -> 50; case 7 -> 40; case 8 -> 30; case 9 -> 20; case 10 -> 10; default -> 0; }; int nl2 = switch (test2) { case 1 -> 100; case 2 -> 90; case 3 -> 80; case 4 -> 70; case 5 -> 60; case 6 -> 50; case 7 -> 40; case 8 -> 30; case 9 -> 20; case 10 -> 10; default -> 0; }; int nl3 = switch (test3) { case 1 -> 100; case 2 -> 90; case 3 -> 80; case 4 -> 70; case 5 -> 60; case 6 -> 50; case 7 -> 40; case 8 -> 30; case 9 -> 20; case 10 -> 10; default -> 0; }; // 计算总分 this.end1 = nl1 + nl2 + nl3; } // 单靶设置方法(如果需要单独修改某一次成绩可以用) public void setC1(int test1) { this.test1 = test1; // 修改后重新计算总分 setScore(this.test1, this.test2, this.test3); } public void setC2(int test2) { this.test2 = test2; setScore(this.test1, this.test2, this.test3); } public void setC3(int test3) { this.test3 = test3; setScore(this.test1, this.test2, this.test3); } // getter方法 public int getC1() { return test1; } public int getC2() { return test2; } public int getC3() { return test3; } public int getEnd1() { return end1; } }
调用逻辑说明
主类的输入逻辑不需要修改,调用lhs[j].setScore(test1, test2, test3)之后,直接调用lhs[j].getEnd1()就能获取换算后的总得分。比如输入1、2、3号靶,返回结果就是100+90+80=270,符合你的需求。
内容的提问来源于stack exchange,提问作者Vincent
相关产品推荐
相关产品推荐

