Java中的循环开关案例

艾曼迪妮

我目前正在研究可在代码中提示学生级别类型的代码(切换用例),并确定每种学生将获得的现金金额。然后,我想对每个学生级别获得的所有现金进行汇总。我是一个初学者,只学习Java几个星期,任何建议都非常感谢。这是我所做的工作,也有注释。

System.out.print("Level code :");
levelCode = input.next().charAt(0);

do {

    switch (levelCode) {
        case 'F':
            System.out.print("Total Foundation student = ");
            studentFoundation = input.nextInt();
            foundationCash = studentFoundation * 50;
            break;
        case 'D':
            System.out.print("Total Diploma student = ");
            studentDiploma = input.nextInt();
            diplomaCash = studentDiploma * 50;
            break;
        case 'B':
            System.out.print("Total Bachelor student = ");
            studentBachelor = input.nextInt();
            bachelorCash = studentBachelor * 70;
            break;
        case 'M':
            System.out.print("Total Master student = ");
            studentMaster = input.nextInt();
            masterCash = studentMaster * 90;
            break;
        case 'P':
            System.out.println("Total PhD student = ");
            studentPhd = input.nextInt();
            phdCash = studentPhd * 90;
            break;
        default:
            System.out.println("Invalid code");
            break;

    }
} while (levelCode < 5); //i dont know what to put here in order to loop the switch case

totalCash = foundationCash + diplomaCash + bachelorCash + masterCash + phdCash; //here i want to calculate all the input entered

System.out.println("Total cash amount = " + totalCash);
安德烈亚斯

假设只希望在default执行案例后返回循环,则可以用不同的方式来执行。

使用标签

LOOP: for (;;) { // forever loop
    System.out.print("Level code :");
    levelCode = input.next().charAt(0);

    switch (levelCode) {
        case 'F':
            // code here
            break LOOP; // <=== break out of the loop, not the switch statement
        case 'D':
            // code here
            break LOOP; // <=== break out of the loop, not the switch statement
        ...
        default:
            // code here
    }
}

使用布尔值

boolean error;
do {
    System.out.print("Level code :");
    levelCode = input.next().charAt(0);

    error = false;
    switch (levelCode) {
        case 'F':
            // code here
            break;
        case 'D':
            // code here
            break;
        ...
        default:
            error = true;
            // code here
    }
} while (error);

使用特殊值,例如null

String levelCode;
do {
    System.out.print("Level code :");
    levelCode = input.next();

    switch (levelCode) {
        case "F":
            // code here
            break;
        case "D":
            // code here
            break;
        ...
        default:
            // code here
            levelCode = null;
    }
} while (levelCode == null);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章