Affichage de Hit and Miss dans Array Java


Je cherche à afficher un hit and miss dans mon projet java. Fondamentalement, j'entre un numéro et le programme frappe ou rate. S'il frappe, il affiche un y, et s'il manque un x. D'après ce que j'ai testé dans le code, cela fonctionne, donnant la sortie disant "Hit" ou "Try again", mais il n'affiche tout simplement pas les x ou les 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);

    }

}
Author: Eran, 2014-11-02

1 answers

Le tableau que vous passez à displayRiver ne contient que des zéros, car vous ne modifiez jamais ses valeurs par défaut.

Par conséquent, votre instruction switch atteint toujours la partie où l'espace vide est affiché:

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

Vous devez affecter 1 ou -1 aux emplacements pertinents du tableau en fonction de l'entrée utilisateur.

Il semble que la boucle de la méthode principale devrait être:

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);
}

Cela suppose que votre méthode promptForInt valide l'entrée (pour s'assurer qu'elle est dans la plage de tableau).

 1
Author: Eran, 2014-11-02 09:04:18