在Array Java中显示命中和缺失

时间:2014-11-02 08:43:11

标签: java arrays

我希望在我的java项目中显示命中和遗漏。基本上,我输入一个数字,程序要么命中,要么错过。如果它命中,它会显示y,如果它错过了x。从我在代码中测试过的,它可以工作,输出“Hit”或“再试一次”,但它不会显示x或y。

public static void displayRiver(int [] river, boolean showShip)
{
    System.out.println();
    System.out.print("|");
    for (int val : river) {
        switch (val) {
        case -1: // No Ship
            System.out.print("x");
            break;
        case 0: // Unknown
            System.out.print(" ");
            break;
        case 1: // Ship Found
      System.out.print("Y");
            break;
        }//switch
        System.out.print("|");
    }//for


}

public static void main (String [] args)
{
    int userInput;
    int length = promptForInt("Enter the length of the river");
    int riverLength[] = new int[length];
    boolean showShip = false;
    displayRiver(riverLength, showShip);
    int randomShipLocation = new Random().nextInt(length);
    int val;


    while(! showShip)
    {
        val = promptForInt("\n" + "Guess again. ");
        displayRiver(riverLength, showShip);

        if(userInput == randomShipLocation)
        {
            System.out.println("\n" +" BOOM!");
            showShip = true;
            displayRiver(riverLength, showShip);
        }
        else if(userInput != randomShipLocation)
               System.out.print(val);

    }

}

1 个答案:

答案 0 :(得分:1)

传递给displayRiver的数组只包含零,因为您永远不会更改其默认值。

因此,您的switch语句总是到达显示空白区域的部分:

    case 0: // Unknown
        System.out.print(" ");
        break;

您应根据用户输入将1-1分配到阵列的相关位置。

看起来main方法中的循环应该是:

while(!showShip)
{
    val = promptForInt("\n" + "Guess again. ");
    if(val == randomShipLocation) // val, instead of userInput
    {
        System.out.println("\n" +" BOOM!");
        showShip = true;
        riverLength[val] = 1; // mark a hit
    }
    else {
        riverLength[val] = -1; // mark a miss
    }
    displayRiver(riverLength, showShip);
}

这假设您的promptForInt方法验证输入(以确保它在数组的范围内)。