Test Foro de elhacker.net SMF 2.1

Programación => Programación General => Java => Mensaje iniciado por: betikano en 14 Mayo 2014, 20:28 PM

Título: cerrar tema
Publicado por: betikano en 14 Mayo 2014, 20:28 PM
Muy buenas, tengo creado un  ArrayList<DirectoryItem> space; y le quiero añadir un email con un metodo, es decir..

Código (java) [Seleccionar]
public boolean addEmail(String email) {
       
      this.space.add(current,email);
      return true;

}


Pero el metodo add me da un fallo

the method add(int, DirectoryItem) in the type Arraylist<DirectoryItem> is not applicable for the arguments (int, String)

alguien sabe que falla? mil gracias de antemano
Título: Re: Duda Arraylist
Publicado por: gordo23 en 15 Mayo 2014, 05:26 AM
El método add toma como parámetro un entero y un objeto DirectoryItem, por que así lo creaste en esta linea:

ArrayList<DirectoryItem> space.

Y vos estás tratando de pasar por parámetro un objeto String.
Título: Re: Duda Arraylist
Publicado por: betikano en 15 Mayo 2014, 09:36 AM
Entonces deberia hacer un downcasting para que me añada el string? Porque necesito añadir el parametro string email, gracias
Título: Re: Duda Arraylist
Publicado por: gordo23 en 15 Mayo 2014, 17:15 PM
¿La clase DirectoryItem la creaste vos? ¿La podés postear?
Título: Re: Duda Arraylist
Publicado por: betikano en 15 Mayo 2014, 17:16 PM
Código (java) [Seleccionar]
package DirectoryPackage;

import java.util.*;

public class DirectoryItem implements Comparable {

   private String name, surname1, surname2;
   private Set<Long> telephones;
   private Set<String> emails;

   public DirectoryItem (String name, String surname1) {
       if (name==null || surname1==null)
           throw new IllegalArgumentException("null values not admitted");
       if (name.trim().equals("") || surname1.trim().equals(""))
           throw new IllegalArgumentException("empty or blank strings not admitted");
       this.name=name.toUpperCase();
       this.surname1=surname1.toUpperCase();
       this.surname2=null;
       this.telephones = new TreeSet<Long>();
       this.emails = new TreeSet<String>();
   }

   public DirectoryItem (String name, String surname1, String surname2) {
       this(name, surname1);
       if (surname2!=null) {
           if (surname2.trim().equals(""))
               throw new IllegalArgumentException("empty or blank strings not admitted");
           this.surname2 = surname2.toUpperCase();
       }
   }

   public String getName() {return this.name;}
   public String getSurname1() {return this.surname1;}
   public String getSurname2() {return this.surname2;}

   // beware, these get methods return a copy not the attributes themselves
   public Collection<Long> getTelephones () {return new TreeSet(this.telephones);}
   public Collection<String> getEmails () {return new TreeSet(this.emails);}

   protected void setSurname2 (String surname2) {this.surname2 = surname2;}

   protected boolean addTelephone(long telephone) {
       // ull! wrapping automatic de telefon (de long a Long)
       return this.telephones.add(telephone);
   }
   protected boolean addEmail (String email) {
       return this.emails.add(email);
   }

   protected boolean removeTelephone (long telephone) {
       return this.telephones.remove(telephone);
   }

   protected boolean removeEmail (String email) {
       return this.emails.remove(email);
   }

   public String toString () {
       
       if (this.name==null || this.surname1==null)
           return "*** Incomplete directory item ***";
       
       String resultat;
       String d,m;

       resultat = this.surname1;
       if (this.surname2 != null) resultat = resultat + this.surname2;
       resultat = resultat + ", " + this.name + "\n";
       resultat = resultat + "  Telephones:\n";
       for (long l : this.telephones) {
           resultat = resultat + "    "+l+"n";
       }
       resultat = resultat + "  Emails:\n";
       for (String s : this.emails) {
           resultat = resultat + "    "+s+"n";
       }
       return resultat;
   }

   public int compareTo(Object o) {
       DirectoryItem altre = (DirectoryItem)o;

       int cmp = this.surname1.compareTo(altre.surname1);
       if (cmp!=0) return cmp;

       // CAS 1: cap dels dos t� segon cognom. El nom decideix
       if (this.surname2 == null && altre.surname2 == null)
           return this.name.compareTo(altre.name);

       // CAS 2: tots dos tenen segon cognom. Primer mirar el segon
       // cognom i si s�n iguals mirar el nom
       if (this.surname2 != null && altre.surname2 != null) {
           cmp = this.surname2.compareTo(altre.surname2);
           if (cmp!=0) return cmp;
           return this.name.compareTo(altre.name);
       }

       // CAS 3: nom�s un dels dos t� segon cognom. �s  menor el que no en t�
       if (this.surname2 == null) return -1;
       else return 1;

   }

   public boolean equals (Object o) {
       try {
           return this.compareTo(o) == 0;
       }
       catch(ClassCastException e) {return false;}
   }

}
Título: Re: Duda Arraylist
Publicado por: Nasty35 en 15 Mayo 2014, 17:23 PM
Prueba con:
Código (java) [Seleccionar]
public boolean addEmail(String email) {
    this.space.add(new DirectoryItem(current, email));
    return true;
}


pd: Has iniciado la variable space? (this.space = new....)
Título: Re: Duda Arraylist
Publicado por: betikano en 15 Mayo 2014, 17:27 PM
Esta iniciado en el constructor

Código (java) [Seleccionar]
public DirectoryPRAC5() {
       this.space = new ArrayList<DirectoryItem>();
       this.current = -1;
   }


pd: el codigo anterior da el error de:

The constructor DirectoryItem (int,String) is undefined
Título: Re: Duda Arraylist
Publicado por: Nasty35 en 15 Mayo 2014, 23:21 PM
Cita de: betikano en 15 Mayo 2014, 17:27 PM
Esta iniciado en el constructor

Código (java) [Seleccionar]
public DirectoryPRAC5() {
       this.space = new ArrayList<DirectoryItem>();
       this.current = -1;
   }


pd: el codigo anterior da el error de:

The constructor DirectoryItem (int,String) is undefined
Sería de ayuda que posteases todo el código, a ciegas es muy difícil.

Ese error indica que tu al constructor le pasas dos parámetros, int y string, y no está definido ningún constructor con esos parámetros, solo hay dos, con dos string, y con tres.
Título: Re: Duda Arraylist
Publicado por: betikano en 15 Mayo 2014, 23:32 PM
Cita de: Nasty35 en 15 Mayo 2014, 23:21 PM
Sería de ayuda que posteases todo el código, a ciegas es muy difícil.

Ese error indica que tu al constructor le pasas dos parámetros, int y string, y no está definido ningún constructor con esos parámetros, solo hay dos, con dos string, y con tres.


package DirectoryPackage;

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


public class DirectoryPRAC5 implements Directory {

    private ArrayList<DirectoryItem> space;
    private int current;
    // no podeu afegir m�s atributs.

    public DirectoryPRAC5() {
        this.space = new ArrayList<DirectoryItem>();
        this.current = -1;
    }

    public boolean addItem(DirectoryItem di) {
        /* COMPLETAR */
        // RECOMANACI�: feu primer una versi� d'aquest m�tode que no
        // contempli cap ordenaci� particular. Feu proves amb aquesta versi�
        // senzilla. Quan creieu que el funcionament �s correcte (llevat
        // de l'ordenaci�) modifique el m�tode de tal manera que l'addici�
        // sigui "ordenada".
       
       //FALTA LO DE ORDENAR QUE PONE AQUI ARRIBA
       
       //retorna true si l'addició s'ha pogut fer efectiva i false en cas contrari
       if(this.space.contains(di)){
          return false;
       }else{
          return true;
       }
    }

    public DirectoryItem getCurrentItem() {
        if (this.current==-1)
            throw new IllegalStateException("No current element");
        return this.space.get(this.current);
    }

    public int getCurrentPosition () {
        if (this.current==-1)
            throw new IllegalStateException("No current element");
        return this.current;
    }

    public int size() {return this.space.size();}

    public DirectoryItem search(String name, String surname1, String surname2) {
        // let's create a target directory item
        if (surname2.trim().equals("")) surname2=null;
        DirectoryItem target = new DirectoryItem(name, surname1, surname2);

        // and now let's perform the search using this target
        int pos = this.search(target);
        if (pos==-1) return null;
        this.current = pos;
        return this.space.get(pos);
    }

    private int search (DirectoryItem di) {
        // returns the position where a DirectoryItem equal to di is located or
        // -1 if none is found
   
       /* COMPLETAR */
       //devuelve la posición de la primera vez
       //que un elemento coincida con el objeto pasado por
       //parámetro. Si el elemento no se encuentra devuelve -1.

       return this.space.indexOf(di);
       
       
    }

    public boolean goFirst() {
        if (this.space.size()==0) return false;

        this.current = 0;
        return true;
    }

    public boolean goLast() {
        if (this.space.size()==0) return false;

        this.current = this.space.size()-1;
        return true;
    }

    public boolean goNext() {
        if (this.current==this.space.size()-1) return false;

        this.current++;
        return true;
    }

    public boolean goPrevious() {
        if (this.current==0) return false;

        this.current--;
        return true;
    }

    public boolean hasNext() {
        return this.current < this.space.size()-1;
    }

    public boolean hasPrevious() {
        return this.current>0;
    }


    public boolean goTo(int pos) {
        if (pos<0 || pos>this.space.size()-1) return false;

        this.current = pos;
        return true;
    }

    public boolean addTelephone(long telephone) {
       
        if (this.current == -1)
            throw new IllegalStateException("no current element");
        /* COMPLETAR */
        if(this.space.contains(telephone)){
           return false;
        }else{
           
           this.space.add(current, telephone);
           return true;
        }
    }

    public boolean addEmail(String email) {
       if (this.current == -1)
            throw new IllegalStateException("no current element");
       
            /* COMPLETAR */
       if(this.space.contains(email)){
          return false;
       }else{
 
          //currentposition guarda en la posicion actual
          //this.space.add(getCurrentPosition(), email);;
   
          this.space.add(new DirectoryItem(current, email));

           return true;
       
       }
    }

    public boolean removeTelephone(long telephone) {
        if (this.current == -1)
            throw new IllegalStateException("no current element");
        /* COMPLETAR */
        if(this.space.contains(telephone)){
           this.space.remove(telephone);
              return true;
         }else{
              return false;
         }
    }

    public boolean removeEmail(String email) {
       if (this.current == -1)
            throw new IllegalStateException("no current element");
        /* COMPLETAR */
       if(this.space.contains(email)){
             this.space.remove(email);
             return true;
        }else{
             return false;
        }
    }

    // m�tode de c�rrega. D�na com a resultat un DirectoryPRAC5 les dades
    // del qual ha obtingut de l'arxiu donat com a par�metre. Si per qualsevol
    // ra� la c�rrega falla (arxiu inexistent, format incorrecte, ...) llavors
    // el resultat retornat ha de ser null
    // Observeu que aquest m�tode �s de classe (STATIC)
    public static DirectoryPRAC5 load(File file) {
        DirectoryPRAC5 resultat = new DirectoryPRAC5();
        /* COMPLETAR */
        // podeu fer la c�rrega de la manera que vosaltres vulgueu. L'�nica
        // restricci� �s que NO feu �s dels mecanismes de serialitzaci�.
       
 
        try { 
            /*Si existe el fichero*/ 
            if(file.exists()){ 
                /*Abre un flujo de lectura a el fichero*/ 
                BufferedReader Flee= new BufferedReader(new FileReader(file)); 
                String Slinea; 
                System.out.println("**********Leyendo Fichero***********"); 
                /*Lee el fichero linea a linea hasta llegar a la ultima*/ 
                while((Slinea=Flee.readLine())!=null) { 
                /*Imprime la linea leida*/     
                System.out.println(Slinea);               
                } 
                System.out.println("*********Fin Leer Fichero**********"); 
                /*Cierra el flujo*/ 
                Flee.close(); 
               
              }else{ 
                System.out.println("La carrega no a sigut possible"); 
                return null;
              } 
        } catch (Exception ex) { 
            /*Captura un posible error y le imprime en pantalla*/   
             System.out.println(ex.getMessage()); 
        } 
       
        return resultat;
       
    }

    // m�tode de descarrega (guardar). Guarda en l'arxiu especificat (primer
    // par�metre) el directori donat (segon par�metre).
    // si pot guardar el directori retorna true i false en cas contrari.
    // Observeu que es tracta d'un m�tode de classe (STATIC) i que, per tant,
    // no �s l'objecte this el que guarda sin� l'objecte donat com a segon
    // par�metre.
    public static boolean save(File file, DirectoryPRAC5 directory) {
        if (directory.size()==0)
            throw new IllegalStateException("Empty directories cannot be saved");
       
        /* COMPLETAR */
        // podeu fer la desc�rrega de la manera que vosaltres vulgueu, mentre
        // sigui compatible amb el m�tode de c�rrega anterior. Recordeu que no
        // podeu fer us dels mecanismes de serialitzaci�.
       
        try { 
            //Si no Existe el fichero lo crea 
             if(!file.exists()){ 
                 file.createNewFile(); 
             } 
            /*Abre un Flujo de escritura,sobre el fichero con codificacion utf-8. 
             *Además  en el pedazo de sentencia "FileOutputStream(Ffichero,true)",
             *true es por si existe el fichero seguir añadiendo texto y no borrar lo que tenia*/ 
            BufferedWriter Fescribe=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file,true))); 
            /*Escribe en el fichero la cadena que recibe la función. 
             *el string "\r\n" significa salto de linea*/ 
            Fescribe.write(directory + "\r\n"); 
            //Cierra el flujo de escritura 
            Fescribe.close();
           
            return true;
           
         } catch (Exception ex) { 
            //Captura un posible error le imprime en pantalla   
            System.out.println(ex.getMessage()); 
         }   
        return false;

}
}
Título: Re: Duda Arraylist
Publicado por: Nasty35 en 17 Mayo 2014, 12:55 PM
Código (java) [Seleccionar]
public boolean addEmail(String email) {
    this.space.add(new DirectoryItem("Nombre", "Apellido").addEmail(email));
    return true;
}
Título: Re: Duda Arraylist
Publicado por: betikano en 17 Mayo 2014, 20:36 PM
Cita de: Nasty35 en 17 Mayo 2014, 12:55 PM
Código (java) [Seleccionar]
public boolean addEmail(String email) {
    this.space.add(new DirectoryItem("Nombre", "Apellido").addEmail(email));
    return true;
}


no hay manera... el add da el siguiente error:

the method add(DirectoryItem) in the type ArrayList<DirectoryItem> is not applicable for the arguments(boolen)
Título: Re: Duda Arraylist
Publicado por: gordo23 en 17 Mayo 2014, 21:23 PM
¿Así funciona?

Código (java) [Seleccionar]
public boolean addEmail(String email) {
    DirectoryItem item = new DirectoryItem("Nombre", "Apellido");
    item.addEmail(email);
    this.space.add(item);
    return true;
}
Título: Re: Duda Arraylist
Publicado por: betikano en 17 Mayo 2014, 21:27 PM
Cita de: gordo23 en 17 Mayo 2014, 21:23 PM
¿Así funciona?

Código (java) [Seleccionar]
public boolean addEmail(String email) {
    DirectoryItem item = new DirectoryItem("Nombre", "Apellido");
    item.addEmail(email);
    this.space.add(item);
    return true;
}


mil gracias!!!!! ya no da error, ara probare si lo ingresa bien, gracias de nuevo!
Título: Re: Duda Arraylist
Publicado por: gordo23 en 17 Mayo 2014, 21:30 PM
Y si lo que quieres hacer es agregar un email al objeto DirectoryItem con posición current en el ArrayList, esto tendrías que hacer:

Código (java) [Seleccionar]
public boolean addEmail(String email) {
   return this.space.get(current).addEmail(email)
}


Porque el método que escribí antes es bastante inútil. Solo te agrega un email en un DirectoryItem creado con "Nombre" y "Apellido", en cambio con este método, si tenés 5 objetos DirectoryItem guardados en el ArrayList, podés recorrerlos uno por uno, cambiando el valor del entero current e ir agregandoles el email.

Saludos.-
Título: Re: Duda Arraylist
Publicado por: betikano en 17 Mayo 2014, 21:35 PM
Cita de: gordo23 en 17 Mayo 2014, 21:30 PM
Y si lo que quieres hacer es agregar un email al objeto DirectoryItem con posición current en el ArrayList, esto tendrías que hacer:

Código (java) [Seleccionar]
public boolean addEmail(String email) {
   return this.space.get(current).addEmail(email)
}


Porque el método que escribí antes es bastante inútil. Solo te agrega un email en un DirectoryItem creado con "Nombre" y "Apellido", en cambio con este método, si tenés 5 objetos DirectoryItem guardados en el ArrayList, podés recorrerlos uno por uno, cambiando el valor del entero current e ir agregandoles el email.

si mejor utilizare este ultimo, mañana haré las pruebas , mil gracias!
Saludos.-