views:

82

answers:

2

Hello.

I have a problem with this code:

import java.util.Random;

public class DotComObjects {

 public int[][] setBarcos(int tablero[][]) {

  boolean repetido; //Variable booleana para comprobar si una casilla ya esta ocupada por otro barco

  do {

   repetido = false; //Suponesmos que no esta ocupada ninguna de las casillas
   Random aRandom = new Random();
   boolean horizontal = aRandom.nextBoolean(); //Booleana al azar para la colocacion del barco. True = horizontal, false = vertical

   if (horizontal == true) { //Si el barco va en horizontal

    int ancho = aRandom.nextInt(tablero.length - 2); //Calculamos al azar la casilla
    int alto = aRandom.nextInt(tablero[0].length); //central del barco (tendra 3)

    if ((tablero[ancho - 1][alto] == 1) || (tablero[ancho][alto] == 1) || (tablero[ancho + 1][alto] == 1)) { //Si una de las casillas ya esta ocupada

     repetido = true; //Variable booleana repetida en true

    }

   } else { //Si el barco va en vertical

    int ancho = aRandom.nextInt(tablero.length); //Calculamos al azar la casilla
    int alto = aRandom.nextInt(tablero[0].length - 2); //central del barco (tendra 3)

    if ((tablero[ancho][alto - 1] == 1) || (tablero[ancho][alto] == 1) || (tablero[ancho][alto + 1] == 1)) { //Si una de las casillas ya esta ocupada

     repetido = true; //Variable booleana repetida en true
    }

   }

  } while (repetido == true); //Repetimos hasta que no haya una casilla ocupada (variable repetido = false)

***  if (horizontal == true) { //Si el barco va en horizontal

***   tablero[ancho - 1][alto] = 1;
***   tablero[ancho][alto] = 1; //Colocamos el barco en el tablero
***   tablero[ancho + 1][alto] = 1;

  } else { //Si el barco va en vertical

***   tablero[ancho][alto - 1] = 1;
***   tablero[ancho][alto] = 1; //Colocamos el barco en el tablero
***   tablero[ancho][alto + 1] = 1;

  }

  return tablero; //Devolvemos el tablero con el barco colocado

 }

}

Its on ***s . Problem is the same for the 3 variables: horizontal/ancho/alto cannot be resolved to a variable.

Thanks.

+3  A: 

This is a clasic scoping problem.

All three of those variables are declared within the do {] while loop, and therefore do not exist outside of it.

To solve the problem, move the declarations to before the do

boolean repetido; //Variable .....
boolean horizontal = false; 
int ancho = 0;
int alto = 0;
do { 

   repetido = false; //Suponesmos ...
   Random aRandom = new Random(); 
   horizontal = aRandom.nextBoolean(); 
   ancho = aRandom.nextInt(tablero.length - 2); //Calculamos ...
   alto = aRandom.nextInt(tablero[0].length); //central ...
James Curran
Thx a lot. Didnt know about it.
Javi
A: 

Your variables are declared inside of the do...while loop, so they cannot be accessed outside of that loop.

murgatroid99
Thx you too. As i said, didnt know it.
Javi