我正在编写一些代码来计算层次结构的某个评估(以点为单位)。我在扫描仪上使用了switch语句(声明为静态变量),由于某种原因,在每个boardType中,“ y”和“ n”的情况都不会中断;他们只是进入下一个boardType案例。我在这里做错了什么?

System.out.println("Are they on board? (y/n)");
isOnBoard = s.nextLine();
switch (isOnBoard){
case "y":
    System.out.println("Chapter, regional, or international board? ");
    boardType = s.nextLine();
    switch (boardType){
    case "chapter":
        System.out.println("Are they chapter president? (y/n)");
        switch(s.nextLine()){
        case "y":
            totalPoints = chapterPres;
            break;
        case "n":
            totalPoints = chapterBoardMember;
            break;
        }
    case "regional":
        System.out.println("Are they regional president? (y/n)");
        switch(s.nextLine()){
        case "y":
            totalPoints = regionalPres;
            break;
        case "n":
            totalPoints = regionalExecutive;
            break;
        }
    case "international":
        System.out.println("Are they international president? (y/n)");
        switch(s.nextLine()){
        case "y":
            totalPoints = internationalPres;
            break;
        case "n":
            totalPoints = internationalExecutive;
            break;
        }
    case "n": break;
}


谢谢大家!

最佳答案

您缺少break语句-用{ }封闭一个块不会使它中断:

case "chapter":
    System.out.println("Are they chapter president? (y/n)");
    switch(s.nextLine()){
    case "y":
        totalPoints = chapterPres;
        break;
    case "n":
        totalPoints = chapterBoardMember;
        break;
    }
    break; // This was missing
case "regional":
    System.out.println("Are they regional president? (y/n)");
    switch(s.nextLine()){
    case "y":
        totalPoints = regionalPres;
        break;
    case "n":
        totalPoints = regionalExecutive;
        break;
    }
    break; // This was missing
case "international":
    System.out.println("Are they international president? (y/n)");
    switch(s.nextLine()){
    case "y":
        totalPoints = internationalPres;
        break;
    case "n":
        totalPoints = internationalExecutive;
        break;
    }
    break; // This was missing
case "n": break;

关于java - 为什么此开关块不起作用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21551106/

10-10 20:26