0

Hi so im a beginner at Java and not all that good at it. But I have to create a battleship program. the directions say that the user has to enter the top-left coordinate and orientation (horizontal and vertical) of 3 different battle ships of lengths 2, 3 and 4. So when the user inputs what row and column they want the position of the ship to be in, i have to replace the element in the 7 x 7 array ( which is "-") and instead put "s" for ship. But it has to be changed in the location where the user wants it and the extra space depending on the length of that ship

so far i have this but it doesn't work.

System.out.println("What row would you like to place the 2 length ship?");
    int row = scan.nextInt();
    System.out.println("What column would you like to place the 2 length ship?");
    int col = scan.nextInt();
    System.out.println("Horizontally or vertically?");
    String hv = scan.next();

char [] [] brdState = new char [7][7];
     for (int r = 0; r < brdState.length; r++)
     {
         for ( int c = 0; c < brdState[r].length; c++)
         {
             brdState [r][c] = '-';
             System.out.print(brdState[r][c] + "\t");
         }
        System.out.println();

if ( hv == "h" || hv == "H");
    {
        int rl = (row - 1);
        for (int c = col; c < col; c++)
        {
            for ( int r = rl; r <= row; r++)
            {
                brdState[row][col] = 's';
                System.out.print(brdState[r][col] + "\t");
                brdState[r][c] = '-';
                System.out.println(brdState[r][c] + "\t");

            }

        }
    }

I need the code to process right where the user wants the length 2 ship to be and then one element to the left of it (horizontal) or right above it (vertical). But i can't program it correctly.

1 Answer 1

1

You would need to change this line:

if ( hv == "h" || hv == "H");

To

if ( hv.equalsIgnoreCase("H"))
             ^^^              ^

This means, you don't need semicolon at the end of if, which makes it as a null statement i.e. irrespective of whether condition is met or not, block of codes between {} will be executed always. Also while comparing two Strings, you need to make use of equals method.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.