switch中的所有情况都会执行,而只有一个应该执行

时间:2016-04-17 14:52:37

标签: java arrays switch-statement

我正在尝试创建一个非常简单的游戏,其中不同类型的几个玩家试图猜测范围内的数字。我做了一个函数来初始化一个玩家阵列,我用switch-case来做它。

出于某种原因,如果我输入一个数字,它会覆盖它之后的所有情况,即使数组中没有足够的单元格。例如,当输入2时,类型为HUMAN的值,它也会创建3和4的情况,并且会创建类型为COMPUTER和GUMBLER的玩家。

以下是代码:

    String name;
    int count = 0;
    System.out.println("How many players will participate?");
    players = new Player[reader.nextByte()];
    for (Player player: players)
    {    
        count++;
        System.out.print("\n1)Name of the player: ");
        name = reader.next();
        System.out.println("What will be its type? WRITE A NUMBER\n1- Monley\n2-Human\n3-Gumbler\n4-Computer");
        switch (reader.nextInt())
        {
            case 1:
                player = new Monkey (name, MAXIMUM, MINIMUM);
                System.out.println("A moneky was created");
            case 2:
                player = new Human (name);
                System.out.println("A human was created");
            case 3:
                player = new Gumbler (name, MAXIMUM, MINIMUM);
                System.out.println("A gummbler was created");
            case 4:
                player = new Computer (name, MAXIMUM, MINIMUM);
                System.out.println("A computer was created");
        }
    }

MAXIMUMMINIMUM是需要猜测的数字的最小和最大数字。 HumanMonkeyComputerGumbler是扩展抽象类Player的类。 players是玩家数组(类型Player)。

2 个答案:

答案 0 :(得分:5)

使用break结束每个案例块。

答案 1 :(得分:2)

在每种情况下,您都需要一个休息声明。见switch in java tutorial

    String name;
    int count = 0;
    System.out.println("How many players will participate?");
    players = new Player[reader.nextByte()];
    for (Player player: players)
    {    
        count++;
        System.out.print("\n1)Name of the player: ");
        name = reader.next();
        System.out.println("What will be its type? WRITE A NUMBER\n1- Monley\n2-Human\n3-Gumbler\n4-Computer");
        switch (reader.nextInt())
        {
            case 1:
                player = new Monkey (name, MAXIMUM, MINIMUM);
                System.out.println("A moneky was created");
                break; 
            case 2:
                player = new Human (name);
                System.out.println("A human was created");
                break;
            case 3:
                player = new Gumbler (name, MAXIMUM, MINIMUM);
                System.out.println("A gummbler was created");
                break;
            case 4:
                player = new Computer (name, MAXIMUM, MINIMUM);
                System.out.println("A computer was created");
        }
    }