Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/382.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java数组中显示命中和未命中_Java_Arrays - Fatal编程技术网

在Java数组中显示命中和未命中

在Java数组中显示命中和未命中,java,arrays,Java,Arrays,我希望在我的java项目中显示成功与失败。基本上,我输入一个数字,程序要么命中,要么未命中。如果命中,则显示一个y,如果未命中一个x。从我在代码中测试的结果来看,它是有效的,输出是“命中”或“重试”,但它只是不显示x或y public static void displayRiver(int [] river, boolean showShip) { System.out.println(); System.out.print("|"); for (int val : r

我希望在我的java项目中显示成功与失败。基本上,我输入一个数字,程序要么命中,要么未命中。如果命中,则显示一个
y
,如果未命中一个
x
。从我在代码中测试的结果来看,它是有效的,输出是“命中”或“重试”,但它只是不显示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);

    }

}

传递给
displayRiver
的数组只包含零,因为您从未更改其默认值

因此,switch语句始终到达显示空白的部分:

    case 0: // Unknown
        System.out.print(" ");
        break;
您应该根据用户输入将
1
-1
分配到阵列的相关位置

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

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
方法验证输入(以确保它在数组的范围内)。

我不明白在案例1中为什么要递归调用
displayRiver
。抱歉,刚才更改了它应该是System.out.print(“Y”);