Mostrar Mensajes

Esta sección te permite ver todos los posts escritos por este usuario. Ten en cuenta que sólo puedes ver los posts escritos en zonas a las que tienes acceso en este momento.


Mensajes - r2montero

Páginas: [1] 2
1
Este es un ejemplo de un mapeo hecho en clase (a mano, sin programarlo con matrices):

Ejercicio de memoria

Considere el siguiente código (del método main) que llama al método calcularDistancia()


Código: [Seleccionar]
String tipoLinea = “Horizontal”;

int coordenadaX1 = 8;
int coordenadaY1 = 10;
int coordenadaX2 = 23;
int coordenadaY2 = 10;

Punto punto1 = new Punto (coordenadaX1, coordenadaY1);
Punto punto2 = new Punto (coordenadaX2, coordenadaY2);
LineaHorizontal linea = new LineaHorizontal (punto1, punto2);
System.out.println(linea. calcularDistancia(tipoLinea));
System.out.println(“Nuevo punto: “);
...
public String calcularDistancia(String tipoLinea ) {
String mensaje = “La distancia entre los puntos de la línea “ + tipoLinea + “ es: “;
int distancia = Math.abs(this.getPunto1().getX() – this. getPunto2().getX());
mensaje += distancia;
return mensaje;
}

Cree la representación del modelo de memoria en java del código anterior. (Los String
puede dejarlos con sólo con la referencia a la dirección de memoria). Debe señalar cuáles segmentos corresponden a los stack frame de los métodos, al run-time-stack y al heap.

a) Cree dicha representación tomando en cuenta que el compilador se encuentra en la línea “Punto punto2 = new Punto (coordenadaX2, coordenadaY2);” y no la ha ejecutado.

b) Cree dicha representación tomando en cuenta que el compilador se encuentra en la línea System.out.println(“Nuevo punto: “);

c) Cree dicha representación tomando en cuenta que el compilador ya terminó de ejecutar el código pero sin borrar la memoria.

SOLUCIONES:
http://wp.me/a7yNnO-2Q
http://wp.me/a7yNnO-2R
http://wp.me/a7yNnO-2S







Salu2.

2
Salu2 a todos!

Tengo la esperanza de que alguien pueda ayudarme:

Nos pidieron programar un ejercicio muy sencillo para venta de productos y calculo de su costo total (al final dejo los códigos).

El problema ahora es que se nos pide integrar una simulación de mapeo de memoria con matrices, pero no tengo idea de como hacerlo, este es el enunciado por si alguien puede guiarme un poco, de antemano gracias!

Citar
Deben programar una representación del modelo de la memoria de Java para la ejecución del código programado. La representación debe ser implementada con dos matrices de String, una que represente el “Runtime Stack” y otra que represente el “Heap”. En la clase de la matriz deberán tener un método para agregar una fila a la matriz y otra para eliminar una serie de filas, desde el final al inicio hasta encontrar una fila null(representa la eliminación de un método o de un objeto).

También deberá tener un método para imprimir la matriz.

Deberán simular la ejecución del programa instrucción por instrucción, lo que quiere decir que para cada instrucción ejecutada deberán ir agregando a las matrices los valores de las instrucciones ejecutadas respectivamente: en una columna las
direcciones de memoria, en otra el valor que corresponde y en otra el nombre de la variable.

Cuando se termina de agregar un un objeto o un método a la matriz deberá agregar una fila null la separación de losmismos.

Sí se encuentra en un método que llama a varios métodos, para estos deberá guardar cálculos intermedios cuando uno de más ya han terminado y queda pendiente uno o más de los métodos.

En el caso de las variables String deben agregar sólo la fila que lo representa y no su espacio en heap ni el de su vector.

No deben realizar el mapeo de los métodos constructores ni de métodos propios de bibliotecas de Java.

Deberán utilizar direcciones ficticias para los segmentos de memoria (similar al formato de mapeo visto en los ejercicios de clase).

Deberán imprimir el contenido de las matrices que representan el “Runtime Stack” y “Heap” en los siguientes tres puntos:

• Se ha llamado al método getBillText del main para el primer objeto bill, dentro del cual se encuentra en el punto de llamar al método calculateCustomsTax, dentro del cual se calculateCustomsTax de Pruducto y en este método ya realizó el cálculo lo retornó pero aún no ha salido de la pila.

• Se ha llamado al método getBillText del main para el segundo objeto bill, dentro del cual se encuentra en el punto de llamar al método calculateTotalBil y en este método ya realizó el cálculo lo retornó pero aún no ha salido de la pila.

• Al final de la ejecución como si no hubieran borrado métodos u objetos. Para esto tendrá que comentar las eliminaciones para los dos puntos anteriores.


Clase Main:

Código: [Seleccionar]
public class Main {

    public static void main(String[] args) {
        Client client = new Client("101110111", "Light", "Yagami");
        Product product = new BookProduct("D. Note", 10000.0, 0.5);
        Bill bill = new Bill(client, product, 3);
        String stringBill = bill.getBillText();
        System.out.println(stringBill);
       
        client = new Client("202220222", "Albert", "Einstein");
        product = new ElectronicProduct("TV plasma", 600000.0, 5);
        bill = new Bill(client, product, 1);
        stringBill = bill.getBillText();
        System.out.println("\n\n-------------------\n\n");
        System.out.println(stringBill);
    }

}


Clase Client:

Código: [Seleccionar]
public class Client {

    private String identityCard;
    private String name;
    private String lastName;

    public Client(String identityCard, String name, String lastName) {
        this.identityCard = identityCard;
        this.name = name;
        this.lastName = lastName;
    }

    public String getIdentityCard() {
        return identityCard;
    }

    public void setIdentityCard(String identityCard) {
        this.identityCard = identityCard;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String toText() {
        return "Cliente : " + identityCard + ", " + name + " " + lastName;
    }

}


Clase Product:

Código: [Seleccionar]
public abstract class Product {

    private String description;
    private double price;
    private double weight;
    private final double customsTax;

    public Product(String name, double price, double weight, double customsTax) {
        this.description = name;
        this.price = price;
        this.weight = weight;
        this.customsTax = customsTax;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public double getWeight() {
        return weight;
    }

    public void setWeight(double weight) {
        this.weight = weight;
    }

    public double getCustomsTax() {
        return customsTax;
    }

    public double calculateCustomsTax() {
        return (customsTax * price);
    }

    public String toText() {
        return "Descripción: " + description + "\nPeso: " + weight + " kg\nImpuesto: " + customsTax + "\nPrecio: " + price;
    }

}


Clase BookProduct:

Código: [Seleccionar]
public class BookProduct extends Product {

    public BookProduct(String name, double price, double weight) {
        super(name, price, weight, Taxes.BOOK_TAX.getTax());
    }

    @Override
    public String toText() {
        return "Producto: Libro\n" + super.toText();
    }
}


Clase ElectronicProduct:

Código: [Seleccionar]
public class ElectronicProduct extends Product {

    public ElectronicProduct(String name, double price, double weight) {
        super(name, price, weight, Taxes.ELECTRONIC_TAX.getTax());
    }

    @Override
    public String toText() {
        return "Producto: Electrónico\n" + super.toText();
    }

}


Clase Bill:

Código: [Seleccionar]
public class Bill {

    private Client client;
    private Product product;
    private int quantity;

    public Bill(Client client, Product product, int quantity) {
        this.client = client;
        this.product = product;
        this.quantity = quantity;
    }

    public Client getClient() {
        return client;
    }

    public void setClient(Client client) {
        this.client = client;
    }

    public Product getProduct() {
        return product;
    }

    public void setProduct(Product product) {
        this.product = product;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    public double calculateCustomsTax() {
        return (product.calculateCustomsTax() * quantity);
    }

    public double calculateTransportCost() {
        return product.getWeight() * quantity * Taxes.TRANSPORT_COST.getTax();
    }

    public double calculateTotalBill() {
        return product.getPrice() + calculateCustomsTax() + calculateTransportCost();
    }

    public String getBillText() {
        return client.toText() + "\n" + product.toText() + "\ncantidad: "
                + quantity + "\nImpuestos de aduanta: " + calculateCustomsTax()
                + "\nCosto de transporte: " + calculateTransportCost()
                + "\nTotal: " + calculateTotalBill();
    }

}


Enum Taxes:

Código: [Seleccionar]
public enum Taxes {
    BOOK_TAX(0.01), ELECTRONIC_TAX(0.25), TRANSPORT_COST(1000);

    private final double TAX;

    Taxes(double tax) {
        this.TAX = tax;
    }

    public double getTax() {
        return TAX;
    }

}

3
Muchas gracias DRANXZ88!

Este ejemplo me viene de maravilla.

Si alguien más tuviese más sugerencias serán siempre bienvenidas...  ;D

4
Salu2!

Como parte de un trabajo de la universidad tenemos que preparar una exposición sobre Archivos/Ficheros de Acceso Aleatorio en Java, ademas de la exposición se le deben plantear a los compañeros algunos ejercicios para resolver en la clase.

Les agradecería mucho si pudieran darme ideas sobre los ejercicios a plantear, o algún lugar donde pueda encontrar ejercicios que no sean muy fáciles, pero que tampoco excedan en dificultad.

Gracias de antemano!

5
Hola a todos!

Podrían darme una idea de como resolver este ejercicio? no quiero que me lo den resuelto, eso no tiene gracia, lo que pido es que alguien me de una idea de como arrancar...

Saludos!

Citar
Un método llamado setUnion que recibe un segundo vector por parámetro. Deberá devolver un String con la unión de los 2 conjuntos (atributo y parámetro). La unión de dos conjuntos son todos los elementos todos los elementos de los 2 conjuntos(vectores) juntos (sin repetidos por teoría de conjuntos). 
      Por ejemplo
         Vector 1:    [1, 4, 8, 90, 10, 5, 7]
         Vector 2:    [4, 6, 8, 10, 23]
         Devuelve:   “1 4 8 90 10 5 7, 6, 23”

6
Muchas gracias por la ayuda!

De hecho el problema era ese. Estaba creando el arreglo, pero no estaba inicializando cada celda con un Table antes de intentar acceder a ellos!

Saludos!

7
Hola amigos!

En un ejercicio de clase nos pidieron programar un Hashtable "a pie", es decir, emular el funcionamiento del Hashtable.

El problema es que no se como resolver la NullPointerException que me esta lanzando la linea 98 de la clase Hashtable.

Les dejo el código para ver si me pueden ayudar y/o dar alguna sugerencia...

Gracias de antemano!

Clase Table.
Código: [Seleccionar]
/**
 * Class Table.
 * To create Table type objects with a key and its corresponding value.
 *
 * @author r2montero.
 * @version 1.0.
 */
public class Table {

    //Atributes
    /**
     * The corresponding key.
     */
    private Object key;

    /**
     * The value linked to the key.
     */
    private Object value;

    /**
     * Default constructor.
     */
    public Table() {
        setKey(null);
        setValue(null);
    }

    /**
     * Constructor with custom key and value.
     *
     * @param key - the corresponding key.
     * @param value - the corresponding value.
     */
    public Table(Object key, Object value) {
        setKey(key);
        setValue(value);
    }

    /**
     *
     * @return
     */
    public Object getValue() {
        return value;
    }

    /**
     *
     * @return
     */
    public Object getKey() {
        return key;
    }

    /**
     *
     * @param value
     */
    public void setValue(Object value) {
        this.value = value;
    }

    /**
     *
     * @param key
     */
    public void setKey(Object key) {
        this.key = key;
    }

}

Clase Hashtable.
Código: [Seleccionar]
/**
 * Class Hashtable
 *
 * This class lets you create tables arrays where you can link keys to values.
 *
 * @author r2montero.
 * @version 1.0.
 */
public class Hashtable {
    //Atributes

    /**
     * Array size.
     */
    private int size;
    /**
     * Object's table array.
     */
    private Table[] hashtable;

    /**
     * Constructs a new, empty hashtable with a default initial capacity of 11.
     */
    public Hashtable() {
        size = 11;
        hashtable = new Table[size];
    }

    /**
     * Constructs a new, empty hashtable with the specified initial capacity.
     *
     * @param size - the initial capacity of the hashtable. Trhrows
     * IllegalArgumentException - if the initial capacity is less than zero.
     */
    public Hashtable(int size) {
        if (size <= 0) {
            throw new IllegalArgumentException();
        } else {
            this.size = size;
            hashtable = new Table[size];
        }
    }

    /**
     * If needed, it creates a new array with space for one more element, and
     * copy into it the elements of the smaller array.
     *
     * @return the new hashtable array.
     */
    private Table[] incrementSize() {
        Table[] tempHashtable = new Table[length() + 1];
        if (isFull()) {
            for (int counter = 0; counter < length(); counter++) {
                tempHashtable[counter] = hashtable[counter];
            }
            return tempHashtable;
        }
        return hashtable;
    }

    /**
     * Check if the array is full.
     *
     * @return true if full, false if not.
     */
    private boolean isFull() {
        try {
            for (int counter = 0; counter < length(); counter++) {
                if (hashtable[counter].getKey() != null && counter == length() - 1) {
                    return true;
                }
            }
        } catch (Exception NullPointerException) {
            return false;
        }
        return false;
    }

    /**
     * Link the specified key to the specified value in this hashtable. Neither
     * the key nor the value can be null.
     *
     * @param key - the hashtable key.
     * @param value - the value. Throws NullPointerException - if the key or
     * value is null.
     */
    public void put(Object key, Object value) {
        if (key != null && value != null) {
            hashtable = incrementSize();
            for (int counter = 0; counter < length(); counter++) {
                try {
                    if (hashtable[counter].getKey() == null && !containsKey(key)) {
                        hashtable[counter].setKey(key);
                        hashtable[counter].setValue(value);
                    }
                } catch (Exception NullPointerException) {
                    hashtable[counter].setKey(key);
                    hashtable[counter].setValue(value);
                }
            }
        } else {
            throw new NullPointerException();
        }
    }

    /**
     * Removes the key (and its corresponding value) from this hashtable.
     *
     * @param key - the key that needs to be removed. Throws
     * NullPointerException - if the key is null
     */
    public void remove(Object key) {
        if (key == null) {
            throw new NullPointerException();
        } else {
            for (int counter = 0; counter < length(); counter++) {
                if (hashtable[counter].getKey() == key) {
                    hashtable[counter].setKey(null);
                    hashtable[counter].setValue(null);
                }
            }
        }
    }

    /**
     * Remove all the keys and his linked values.
     */
    public void clear() {
        for (int counter = 0; counter < length(); counter++) {
            hashtable[counter].setKey(null);
            hashtable[counter].setValue(null);
        }
    }

    /**
     * Tests if the specified object is a key in this hashtable.
     *
     * @param key - possible key.
     * @return true if the key is in hashtable, false if not. Throws
     * NullPointerException - if the key is null.
     */
    public boolean containsKey(Object key) {
        if (key == null) {
            throw new NullPointerException();
        } else {
            for (int counter = 0; counter < length(); counter++) {
                if (hashtable[counter].getKey().equals(key)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * Tests if the specified object is a value in this hashtable.
     *
     * @param value - possible value.
     * @return true if the value is in hashtable, false if not.
     */
    public boolean containsValue(Object value) {
        for (int counter = 0; counter < length(); counter++) {
            if (hashtable[counter].getValue().equals(value)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Check if the array is empty.
     *
     * @return true if empty, false if not.
     */
    public boolean isEmpty() {
        if (size() == 0) {
            return true;
        }
        return false;
    }

    /**
     * Return the hashtable length.
     *
     * @return the length.
     */
    public int length() {
        return hashtable.length;
    }

    /**
     * Returns the number of keys in the hashtable.
     *
     * @return the number of keys in this hashtable.
     */
    public int size() {
        int hashSize = 0;
        try {
            for (int counter = 0; counter < hashtable.length; counter++) {
                if (hashtable[counter].getKey() != null) {
                    hashSize++;
                }
            }
        } catch (Exception e) {
            return hashSize;
        }
        return hashSize;
    }

    /**
     * @param key - the hashtable key. Returns the value to which the specified
     * key is linked. Throws NullPointerException - if the specified key is
     * null.
   *
     */
    public Object get(Object key) {
        Object value = "El campo " + key + " no contiene ningun valor.";
        if (key == null) {
            throw new NullPointerException();
        } else {
            for (int counter = 0; counter < hashtable.length; counter++) {
                if (hashtable[counter].getKey().equals(key)) {
                    if (hashtable[counter].getValue() != null) {
                        value = hashtable[counter].getValue();
                    }
                }
            }
        }

        return value;
    }

    /**
     * Returns a string representation of this Hashtable.
     *
     * @return a string representation of this hashtable.
     */
    @Override
    public String toString() {
        String text = null;
        for (int counter = 0; counter < length(); counter++) {
            text += hashtable[counter].getKey() + " " + hashtable[counter].getValue() + "\n";
        }
        return text;
    }
}

Clase Main.
Código: [Seleccionar]
public class Main {

    public static void main(String[] args) {
        Hashtable hashtable11 = new Hashtable();
        Hashtable hashtable3 = new Hashtable(3);

        hashtable11.put(1, "Navas");
        hashtable11.put(19, "Miller");
        hashtable11.put(6, "Duarte");
        hashtable11.put(3, "Gonzalez");
        hashtable11.put(8, "Diaz");
        hashtable11.put(5, "Borges");
        hashtable11.put(17, "Tejeda");
        hashtable11.put(16, "Gamboa");
        hashtable11.put(14, "Brenes");
        hashtable11.put(10, "Ruiz");
        hashtable11.put(9, "Campbell");

        System.out.println("Alineacion de C.R. vrs. Inglaterra en Brasil 2014\n" + hashtable11.toString());

    }
}

8
Muchas gracias por la retroalimentación Alex!

En la última parte del ejercicio 2, admito que la solución me pareció bastante chapucera, pero no se me ocurrió nada más...
En ese caso me devuelve al inicio total de la entrada, es decir tengo que volver a anotar el nombre del estudiante y la nota, ¿Cómo podría hacer para que en caso de digitar una nota incorrecta el programa me solicitara SOLO la nota nuevamente y no también el nombre?

Saludos!

9
Por favor revisar y dar las indicaciones correspondientes...  Ejercicio CU00903C del curso de programación en Java avanzado.

Ejercicio 1.
Código: [Seleccionar]
import java.util.Scanner;
public class Ejercicio1 {
 
 
  public static void main(String[] args) {
   final int SIZE = 5;
    int[] five = new int[SIZE];
    int counter = 0;
    Scanner readInt = new Scanner(System.in);
    char leter = 97;
   
    while(counter < five.length) {
     
      System.out.print("Escriba el entero " + leter + ": ");
      five[counter] = readInt.nextInt();
      counter++;
      leter++;
    }
   
    counter = 0;
   
    while(counter < five.length) {
     
      System.out.println("En el  índice " + counter + " está el valor " + five[counter]);
      counter++;
    }
   
  }

}

Ejercicio 2.
Código: [Seleccionar]
import java.util.Scanner;
public class Ejercicio2 {

  public static void main(String[] args) {
    final int SIZE = 2;
    String[] name = new String[SIZE];
    String[] status = new String[SIZE];
    double[] rate = new double[SIZE];
    Scanner read = new Scanner(System.in);
       
    for( int counter = 0; counter < SIZE; counter++) {
     
      System.out.print("Indique el nombre del estudiante: ");
      name[counter] = read.next();
      System.out.print("Indique la nota de : " + name[counter]);
      rate[counter] = read.nextDouble();
     
      if(rate[counter] >= 0 && rate[counter] <= 4.99) {
        status[counter] = "Suspenso";
      }
      else if(rate[counter] >= 5 && rate[counter] <= 6.99) {
        status[counter] = "Bien";
      }
      else if(rate[counter] >= 7 && rate[counter] <= 8.99) {
        status[counter] = "Notable";
      }
      else if(rate[counter] >= 9 && rate[counter] <= 10) {
        status[counter] = "Sobresaliente";
      }
      else {
        System.out.println("Digite una nota válida (entre 0 y 10) \n");
        counter--;
      }     
           
    }
   
    for( int counter = 0; counter < SIZE; counter++) {
      System.out.println("Estudiante: " + name[counter] + "   Nota: " + rate[counter] + "   Condicion: " + status[counter]);
    }
  }
}

Saludos!!

10
Gracias Ogramar!

Al final me decidí por Brackets http://brackets.io/ que me pareció bastante interesante.

Saludos!

11
Hola a tod@s!

Voy a comenzar el curso de HTML https://www.aprenderaprogramar.com/index.php?option=com_content&view=category&id=69&Itemid=192 Sin embargo, trabajo en Linux y me gustaría que me recomendaran una alternativa a Notepad++ (CU00708B).

Gracias de antemano!

Salu2!

12
Hola de nuevo!

Necesito ayuda! Estoy tratando de lograr que el jugador humano coloque sus naves en el tablero, ya logré que la máquina colocara aleatoriamente los suyos.

Pero no tengo idea de cómo hacer para que el usuario pueda colocar los suyos...

Saludos!

13
Muchas Gracias Ogramar!

Me ahorrás mucho trabajo.

Ahora lo que me tiene en problemas es la colocación de las naves...

Saludos!

14
Citar
No has explicado cuántas naves existen

Respecto a este punto: Son en total 5 naves:
1 de cinco casillas;
1 de cuatro casillas;
2 de tres casillas;
1 de dos casillas.

El jugador deberá posicionar sus manos de forma manual y la colocación de las naves del sistema de debe generar de forma aleatoria.

Saludos!

15
Clase Array que maneja el ArrayList de los jugadores al cargar los archivos del juego:
Código: [Seleccionar]
package starwarsbattleship;

import java.util.ArrayList;

/**
 *
 * @author Jose Ricardo Rojas Montero. A24418
 */
public class Array {
   
    private static Array array;
    private ArrayList<Player> playersArray = new ArrayList();

    private Array() {
       
    }
   
    public static Array getInstance() {
        if(array == null) {
            array = new Array();
        }
       
        return array;
    }
     
    public void addPlayer(Player player) {
        playersArray.add(player);
    }

    public Player getPlayer(int index) {
        return playersArray.get(index);
    }
   
    public ArrayList<Player> getPlayersArray() {
        return playersArray;
    }
       
}

Clase FilesManager que se encargara de la gestión de los archivos (de momento solo un .csv pero se pide implementar ficheros de acceso aleatorio, ficheros binarios y ficheros de texto(.csv) en determinadas partes del juego).
Código: [Seleccionar]
package starwarsbattleship;

import java.io.*;
import java.util.StringTokenizer;

/**
 *
 * @author Jose Ricardo Rojas Montero. A24418
 */
public class FilesManager {
   
    private static FilesManager saver;

    private FilesManager() {
    }
   
    public static FilesManager getInstance() {
        if(saver == null){
            saver = new FilesManager();
        }
        return saver;
    }

    public void SavePlayer(Player player, String fileName, boolean addToExisting) {
        File file = new File(fileName);
        boolean header = false;
       
        if (file.exists() && !addToExisting) {
            file.delete();
            header = true;
        }
        if(!file.exists()){
            header = true;
        }

        FileWriter outputFlow = null;
        BufferedWriter output = null;

        try {
            outputFlow = new FileWriter(file, addToExisting);
            output = new BufferedWriter(outputFlow);
           
            if(header) {
                output.write("Nombre;Nickname;Passwor;Minutos;Segundos");
                output.newLine();
            }
                       
            output.write(player.getName()+";");
            output.write(player.getNickname()+";");
            output.write(player.getPassword()+";");
            output.write(Integer.toString(player.getTime().getMinutes())+";");
            output.write(Integer.toString(player.getTime().getSeconds()));
            output.newLine();
           
            output.close();
            outputFlow.close();
        } catch (IOException e) {
            System.out.println("Error");
            e.printStackTrace();
        } finally {
            try {
                output.close();
                outputFlow.close();
            } catch (IOException e) {
                System.out.println("Error al cerrar");
                e.printStackTrace();
            }
        }
    }
   
    public Player readPlayers(){
        Player player;
       
        try{
            FileReader readFile = new FileReader("players.csv");
            BufferedReader input = new BufferedReader(readFile);
           
            String name,
                   nickname,
                   password;
            Time time;
            int minutes;
            int seconds;
           
            String line;
            input.readLine();
           
            while((line = input.readLine()) !=null) {
                StringTokenizer txt = new StringTokenizer(line, ";");
               
                name = txt.nextToken();
                nickname = txt.nextToken();
                password = txt.nextToken();
                minutes = Integer.parseInt(txt.nextToken());
                seconds = Integer.parseInt(txt.nextToken());
                time = new Time(minutes, seconds);
               
                player = new Player(name, nickname, password, time);
                return player;
            }
        }
        catch(IOException e) {
            System.out.println("Error");
            e.getStackTrace();
        }
        return null;
    }
}

Clase GameFlow, donde pretendía meter la parte del desarrollo lógico del juego:
Código: [Seleccionar]
package starwarsbattleship;

/**
 *
 * @author r2montero
 */
public class GameFlow {
    private int boardSize;
    private int [][] computerBoard = new int [boardSize][boardSize];
    private int [][] playerBoard = new int [boardSize][boardSize];
   
    public void StartGame() {
        for(int row = 0; row < boardSize; row++) {
            for(int column = 0; column < boardSize; column++) {
                computerBoard[row][column] = 0;
                playerBoard[row][column] = 0;
            }
        }
    }
   
    /*public boolean isIntoBoardBounds() {
       
    }*/
}

De nuevo muchas gracias! y por favor disculpa cualquier molestia...

Saludos!

16
...
Clase SignIn, para el registro de jugadores:
Código: [Seleccionar]
package starwarsbattleship;

import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;

/**
 *
 * @author r2montero
 */
public class SignIn extends javax.swing.JFrame {
    //private boolean addToExisting = true;

    /**
     * Creates new form SignIn
     */
    public SignIn() {
        initComponents();
        setTitle("Registro de Jugadores");
        setIconImage(new ImageIcon(getClass().getResource("/images/deathstarico.png")).getImage());
        ((JPanel) getContentPane()).setOpaque(false);
        ImageIcon milleniumwindow = new ImageIcon(this.getClass().getResource("/images/falconwindow.jpg"));
        JLabel background = new JLabel();
        background.setIcon(milleniumwindow);
        getLayeredPane().add(background, JLayeredPane.FRAME_CONTENT_LAYER);
        background.setBounds(0, 0, milleniumwindow.getIconWidth(), milleniumwindow.getIconHeight());
        Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension frame = getSize();
        setLocation((screen.width - frame.width) / 2,(screen.height - frame.height) / 2);
    }
   
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {

        namelbl = new javax.swing.JLabel();
        nicknamelbl = new javax.swing.JLabel();
        passwordlbl = new javax.swing.JLabel();
        nametxt = new javax.swing.JTextField();
        nicknametxt = new javax.swing.JTextField();
        passwordtxt = new javax.swing.JPasswordField();
        passrptlbl = new javax.swing.JLabel();
        passtxt = new javax.swing.JPasswordField();
        accept = new javax.swing.JButton();
        cancel = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        namelbl.setFont(new java.awt.Font("Star Jedi Logo DoubleLine2", 0, 14)); // NOI18N
        namelbl.setForeground(java.awt.Color.yellow);
        namelbl.setText("Nombre del Piloto");

        nicknamelbl.setFont(new java.awt.Font("Star Jedi Logo DoubleLine2", 0, 14)); // NOI18N
        nicknamelbl.setForeground(java.awt.Color.yellow);
        nicknamelbl.setText("Nickname");

        passwordlbl.setFont(new java.awt.Font("Star Jedi Logo DoubleLine2", 0, 14)); // NOI18N
        passwordlbl.setForeground(java.awt.Color.yellow);
        passwordlbl.setText("Contraseña");

        passrptlbl.setFont(new java.awt.Font("Star Jedi Logo DoubleLine2", 0, 13)); // NOI18N
        passrptlbl.setForeground(java.awt.Color.yellow);
        passrptlbl.setText("Repita la Contraseña");

        accept.setText("Aceptar");
        accept.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                acceptActionPerformed(evt);
            }
        });

        cancel.setText("Cancelar");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(84, 84, 84)
                        .addComponent(accept, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(passrptlbl)
                            .addComponent(passwordlbl)
                            .addComponent(nicknamelbl)
                            .addComponent(namelbl))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(nametxt, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(24, 24, 24)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(nicknametxt, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(passwordtxt, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(passtxt, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(cancel, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE))))))
                .addContainerGap(22, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(23, 23, 23)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(namelbl)
                    .addComponent(nametxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(13, 13, 13)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(nicknamelbl)
                    .addComponent(nicknametxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(passwordlbl)
                    .addComponent(passwordtxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(passrptlbl)
                    .addComponent(passtxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(61, 61, 61)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(accept)
                    .addComponent(cancel))
                .addContainerGap(30, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                       

    private void acceptActionPerformed(java.awt.event.ActionEvent evt) {                                       
        String pName = nametxt.getText();
        String pNick = nicknametxt.getText();
        String pPassword = new String(passwordtxt.getPassword());
        String pPass = new String(passtxt.getPassword());
        Player player;

        if (pPassword.equals(pPass)) {
            player = new Player(pName, pNick, pPass);
            Array saveToArrayList = Array.getInstance();
            saveToArrayList.addPlayer(player);
           
           
            /*FilesManager save = FilesManager.getInstance();
            boolean newFile = true;
           
            if(addToExisting){
               addToExisting = false;
               newFile = false;
            }
           
            save.SavePlayer(player, "players.csv", newFile);*/
           
        } else {
            BadPass msg = new BadPass();
            msg.setVisible(true);
            dispose();
        }
    }                                     

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(SignIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(SignIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(SignIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(SignIn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new SignIn().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton accept;
    private javax.swing.JButton cancel;
    private javax.swing.JLabel namelbl;
    private javax.swing.JTextField nametxt;
    private javax.swing.JLabel nicknamelbl;
    private javax.swing.JTextField nicknametxt;
    private javax.swing.JLabel passrptlbl;
    private javax.swing.JPasswordField passtxt;
    private javax.swing.JLabel passwordlbl;
    private javax.swing.JPasswordField passwordtxt;
    // End of variables declaration                   
}


Clase BadPass, que indica un mensaje en caso de que las contraseñas no coincidan:
Código: [Seleccionar]
package starwarsbattleship;

import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;

/**
 *
 * @author r2montero
 */
public class BadPass extends javax.swing.JFrame {
   
    /**
     * Creates new form BadPass
     */
    public BadPass() {
        initComponents();
        setTitle("Contraseñas no coinciden");
        setIconImage(new ImageIcon(getClass().getResource("/images/deathstarico.png")).getImage());
        ((JPanel)getContentPane()).setOpaque(false);
        ImageIcon vader = new ImageIcon(this.getClass().getResource("/images/vadermsg.jpg"));
        JLabel background = new JLabel();
        background.setIcon(vader);
        getLayeredPane().add(background,JLayeredPane.FRAME_CONTENT_LAYER);
        background.setBounds(0, 0, vader.getIconWidth(), vader.getIconHeight());
       
        setLocationRelativeTo(null);
       
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        accept = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);
        setType(java.awt.Window.Type.POPUP);

        jLabel1.setFont(new java.awt.Font("Ubuntu", 1, 16)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(164, 21, 19));
        jLabel1.setText("¡Las contraseñas digitadas");

        jLabel2.setFont(new java.awt.Font("Ubuntu", 1, 16)); // NOI18N
        jLabel2.setForeground(new java.awt.Color(164, 21, 19));
        jLabel2.setText("deben ser iguales!");

        jLabel3.setFont(new java.awt.Font("Ubuntu", 1, 16)); // NOI18N
        jLabel3.setForeground(new java.awt.Color(164, 21, 19));
        jLabel3.setText("Intentelo otra vez");

        accept.setText("Aceptar");
        accept.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                acceptMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(accept, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel3)))
                .addContainerGap(186, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(jLabel2)
                .addGap(18, 18, 18)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 28, Short.MAX_VALUE)
                .addComponent(accept)
                .addGap(25, 25, 25))
        );

        pack();
    }// </editor-fold>                       

    private void acceptMouseClicked(java.awt.event.MouseEvent evt) {                                   
        SignIn back = new SignIn();
        back.setVisible(true);
        dispose();
    }                                   

   
   
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(BadPass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(BadPass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(BadPass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(BadPass.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new BadPass().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton accept;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    // End of variables declaration                   
}

Cont...

17
Hola César! Y muchas gracias!

La verdad es que si he estado bastante enredado, siempre me pasa que me cuesta bastante saber por donde arrancar, voy a analizar tus sugerencias para ir adaptándolas y descomplicarme un poco la vida...  :-\

Aprovecho también para copiar el código que tengo hasta ahora para que lo veas y me digas que opinas:

Clase Player:
Código: [Seleccionar]
package starwarsbattleship;


/**
 *
 * @author r2montero
 */
public class Player {
    private String name,
                   nickname,
                   password;
   
    private Time time;
   
    public Player(String name, String nickname, String password, Time time) {
        this.name = name;
        this.nickname = nickname;
        this.password = password;
        this.time = time;
    }
   
    public Player(String name, String nickname, String password) {
        this(name, nickname, password, new Time());
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getName() {
        return name;
    }

    public String getNickname() {
        return nickname;
    }

    public String getPassword() {
        return password;
    }
   
     public Time getTime() {
        return time;
    }

    @Override
    public String toString() {
        String text = "";
       
        text += " "+name;
        text += " "+nickname;
        text += " "+password;
        text += " "+time.getMinutes();
        text += ":"+time.getSeconds();
       
        return text;
    }
}

Clase Time:
Código: [Seleccionar]
package starwarsbattleship;

/**
 *
 * @author r2montero
 */
public class Time {
    private int minutes;
    private int seconds;
   
    public Time(int minutes, int seconds) throws IllegalArgumentException {
        if(minutes < 0 || minutes > 4 || seconds < 0 || seconds > 59) {
            throw new IllegalArgumentException();
        }
        this.minutes = minutes;
        this.seconds = seconds;
    }
   
    public Time() {
        this(04, 59);
    }

    public int getMinutes() {
        return minutes;
    }

    public void setMinutes(int minutes) {
        this.minutes = minutes;
    }

    public int getSeconds() {
        return seconds;
    }

    public void setSeconds(int seconds) {
        this.seconds = seconds;
    }
}

Cont...

18
Hola amigos de aprenderaprogramar!

Acudo a ustedes una vez más en busca de iluminación  ::)

Tengo que programar una versión del juego batalla naval en Java, ya tengo algunas partes aisladas como ventanas de inicio, registro de nuevos jugadores y login pero se me ha hecho bastante difícil arrancar la parte principal del juego:

Tengo que montar un tablero de 15x15 para el nivel principiante, 20x20 para el intermedio y 30x30 avanzado.  El juego no es para dos jugadores es para jugar contra la computadora únicamente y la parte gráfica de los tableros debe ser independiente del funcionamiento "interno" o lógico del juego, estoy pensando en tener 2 matrices, una de botones (gráficos) y la otra de ceros (agua) y unos (barcos y minas) ademas debo tener un cronómetro con hilos, ya que el juego tiene limite tiempo y en caso de que el jugador golpee una mina mala se le penalizará con tiempo y/o con devolución de impactos atinados (de forma aleatoria) y en caso de golpear una mina buena se le premiará con tiempo extra. Además se debe llevar un registro de los mejores 10 récords de entré todos los jugadores.

Respecto a la colocación de las naves estas deben de poder colocarse en cualquier lugar del tablero en forma vertical u horizontal respetando los límites del tablero, una vez colocados los barcos, las minas en total 6 se deben colocar aleatoriamente en cualquiera de los espacios que no estén ocupados por barcos.

No se bien como manejar la lógica de todo lo anterior  :-[ y me vendrían muy bien las sugerencias e ideas.

De antemano quedo muy agradecido por su atención y su ayuda!

Saludos!

19
Hola, muchas gracias por la ayuda! Ya siento que estoy corriendo contra el tiempo, la entrega es el 11 de octubre  :-\ :'(

Un par de dudas más:

Que me sugieres para crear el polígono de N lados? Estaba pensando tal vez en un vector que vaya pidiendo n pares de coordenadas de acuerdo a n cantidad de lados, pero no se me ocurre como validar que los lados sean iguales... :(

Por otro lado tengo un método de ordenamiento burbuja para ordenar las figuras por área, pero se supone que no debo repetir código, cómo hacer para que el mismo método me sirva también para ordenar las figuras por perímetro y apotema?

Este es el código:
Código: [Seleccionar]
public void bubbleSort() {
        Polygon tempVar;
       
       
        for(int counter = 0; counter < polygonVector.length; counter++) {
            for(int counter2 = 0; counter2 < polygonVector.length - counter; counter++) {
                if(polygonVector[counter2 - 1].calcArea() > polygonVector[counter2].calcArea()) {
                    tempVar = polygonVector[counter2 - 1];
                    polygonVector[counter2 - 1] = polygonVector[counter2];
                    polygonVector[counter2] = tempVar;
                }
            }
        }       
    }


Como hacer para que el método cambie el  .calcArea() por un .calcPerimeter() o un .calcApothem de acuerdo al caso, esto para hacer una llamada al método y no tener que escribirlo tres veces?

20
Comunidad / Re:Tarde pero seguro... Hola! Saludo y me desahogo.
« en: 29 de Septiembre 2015, 09:42 »
Muchas Gracias César!

La verdad es que en el foro me han ayudado bastante principalmente Ogramar y vos. Pues a seguir echando pa'lante esperando que todo salga bien.

Saludos!

Páginas: [1] 2

Sobre la educación, sólo puedo decir que es el tema más importante en el que nosotros, como pueblo, debemos involucrarnos.

Abraham Lincoln (1808-1865) Presidente estadounidense.

aprenderaprogramar.com: Desde 2006 comprometidos con la didáctica y divulgación de la programación

Preguntas y respuestas

¿Cómo establecer o cambiar la imagen asociada (avatar) de usuario?
  1. Inicia sesión con tu nombre de usuario y contraseña.
  2. Pulsa en perfil --> perfil del foro
  3. Elige la imagen personalizada que quieras usar. Puedes escogerla de una galería de imágenes o subirla desde tu ordenador.
  4. En la parte final de la página pulsa el botón "cambiar perfil".