elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Curso de javascript por TickTack


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  Java
| | | |-+  cerrar tema
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] 2 Ir Abajo Respuesta Imprimir
Autor Tema: cerrar tema  (Leído 5,833 veces)
betikano

Desconectado Desconectado

Mensajes: 16


Ver Perfil
cerrar tema
« 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
  1. public boolean addEmail(String email) {
  2.  
  3.       this.space.add(current,email);
  4.       return true;
  5.  
  6. }

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


« Última modificación: 19 Mayo 2014, 23:39 pm por betikano » En línea

gordo23

Desconectado Desconectado

Mensajes: 38


Ver Perfil
Re: Duda Arraylist
« Respuesta #1 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.


En línea

betikano

Desconectado Desconectado

Mensajes: 16


Ver Perfil
Re: Duda Arraylist
« Respuesta #2 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
En línea

gordo23

Desconectado Desconectado

Mensajes: 38


Ver Perfil
Re: Duda Arraylist
« Respuesta #3 en: 15 Mayo 2014, 17:15 pm »

¿La clase DirectoryItem la creaste vos? ¿La podés postear?
En línea

betikano

Desconectado Desconectado

Mensajes: 16


Ver Perfil
Re: Duda Arraylist
« Respuesta #4 en: 15 Mayo 2014, 17:16 pm »

Código
  1. package DirectoryPackage;
  2.  
  3. import java.util.*;
  4.  
  5. public class DirectoryItem implements Comparable {
  6.  
  7.    private String name, surname1, surname2;
  8.    private Set<Long> telephones;
  9.    private Set<String> emails;
  10.  
  11.    public DirectoryItem (String name, String surname1) {
  12.        if (name==null || surname1==null)
  13.            throw new IllegalArgumentException("null values not admitted");
  14.        if (name.trim().equals("") || surname1.trim().equals(""))
  15.            throw new IllegalArgumentException("empty or blank strings not admitted");
  16.        this.name=name.toUpperCase();
  17.        this.surname1=surname1.toUpperCase();
  18.        this.surname2=null;
  19.        this.telephones = new TreeSet<Long>();
  20.        this.emails = new TreeSet<String>();
  21.    }
  22.  
  23.    public DirectoryItem (String name, String surname1, String surname2) {
  24.        this(name, surname1);
  25.        if (surname2!=null) {
  26.            if (surname2.trim().equals(""))
  27.                throw new IllegalArgumentException("empty or blank strings not admitted");
  28.            this.surname2 = surname2.toUpperCase();
  29.        }
  30.    }
  31.  
  32.    public String getName() {return this.name;}
  33.    public String getSurname1() {return this.surname1;}
  34.    public String getSurname2() {return this.surname2;}
  35.  
  36.    // beware, these get methods return a copy not the attributes themselves
  37.    public Collection<Long> getTelephones () {return new TreeSet(this.telephones);}
  38.    public Collection<String> getEmails () {return new TreeSet(this.emails);}
  39.  
  40.    protected void setSurname2 (String surname2) {this.surname2 = surname2;}
  41.  
  42.    protected boolean addTelephone(long telephone) {
  43.        // ull! wrapping automatic de telefon (de long a Long)
  44.        return this.telephones.add(telephone);
  45.    }
  46.    protected boolean addEmail (String email) {
  47.        return this.emails.add(email);
  48.    }
  49.  
  50.    protected boolean removeTelephone (long telephone) {
  51.        return this.telephones.remove(telephone);
  52.    }
  53.  
  54.    protected boolean removeEmail (String email) {
  55.        return this.emails.remove(email);
  56.    }
  57.  
  58.    public String toString () {
  59.  
  60.        if (this.name==null || this.surname1==null)
  61.            return "*** Incomplete directory item ***";
  62.  
  63.        String resultat;
  64.        String d,m;
  65.  
  66.        resultat = this.surname1;
  67.        if (this.surname2 != null) resultat = resultat + this.surname2;
  68.        resultat = resultat + ", " + this.name + "\n";
  69.        resultat = resultat + "  Telephones:\n";
  70.        for (long l : this.telephones) {
  71.            resultat = resultat + "    "+l+"n";
  72.        }
  73.        resultat = resultat + "  Emails:\n";
  74.        for (String s : this.emails) {
  75.            resultat = resultat + "    "+s+"n";
  76.        }
  77.        return resultat;
  78.    }
  79.  
  80.    public int compareTo(Object o) {
  81.        DirectoryItem altre = (DirectoryItem)o;
  82.  
  83.        int cmp = this.surname1.compareTo(altre.surname1);
  84.        if (cmp!=0) return cmp;
  85.  
  86.        // CAS 1: cap dels dos t&#65533; segon cognom. El nom decideix
  87.        if (this.surname2 == null && altre.surname2 == null)
  88.            return this.name.compareTo(altre.name);
  89.  
  90.        // CAS 2: tots dos tenen segon cognom. Primer mirar el segon
  91.        // cognom i si s&#65533;n iguals mirar el nom
  92.        if (this.surname2 != null && altre.surname2 != null) {
  93.            cmp = this.surname2.compareTo(altre.surname2);
  94.            if (cmp!=0) return cmp;
  95.            return this.name.compareTo(altre.name);
  96.        }
  97.  
  98.        // CAS 3: nom&#65533;s un dels dos t&#65533; segon cognom. &#65533;s  menor el que no en t&#65533;
  99.        if (this.surname2 == null) return -1;
  100.        else return 1;
  101.  
  102.    }
  103.  
  104.    public boolean equals (Object o) {
  105.        try {
  106.            return this.compareTo(o) == 0;
  107.        }
  108.        catch(ClassCastException e) {return false;}
  109.    }
  110.  
  111. }
« Última modificación: 15 Mayo 2014, 17:28 pm por #!drvy » En línea

Nasty35

Desconectado Desconectado

Mensajes: 77


Ver Perfil
Re: Duda Arraylist
« Respuesta #5 en: 15 Mayo 2014, 17:23 pm »

Prueba con:
Código
  1. public boolean addEmail(String email) {
  2.    this.space.add(new DirectoryItem(current, email));
  3.    return true;
  4. }

pd: Has iniciado la variable space? (this.space = new....)
En línea

betikano

Desconectado Desconectado

Mensajes: 16


Ver Perfil
Re: Duda Arraylist
« Respuesta #6 en: 15 Mayo 2014, 17:27 pm »

Esta iniciado en el constructor

Código
  1. public DirectoryPRAC5() {
  2.        this.space = new ArrayList<DirectoryItem>();
  3.        this.current = -1;
  4.    }

pd: el codigo anterior da el error de:

The constructor DirectoryItem (int,String) is undefined
« Última modificación: 15 Mayo 2014, 17:28 pm por #!drvy » En línea

Nasty35

Desconectado Desconectado

Mensajes: 77


Ver Perfil
Re: Duda Arraylist
« Respuesta #7 en: 15 Mayo 2014, 23:21 pm »

Esta iniciado en el constructor

Código
  1. public DirectoryPRAC5() {
  2.        this.space = new ArrayList<DirectoryItem>();
  3.        this.current = -1;
  4.    }

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.
En línea

betikano

Desconectado Desconectado

Mensajes: 16


Ver Perfil
Re: Duda Arraylist
« Respuesta #8 en: 15 Mayo 2014, 23:32 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;

}
}
En línea

Nasty35

Desconectado Desconectado

Mensajes: 77


Ver Perfil
Re: Duda Arraylist
« Respuesta #9 en: 17 Mayo 2014, 12:55 pm »

Código
  1. public boolean addEmail(String email) {
  2.    this.space.add(new DirectoryItem("Nombre", "Apellido").addEmail(email));
  3.    return true;
  4. }
En línea

Páginas: [1] 2 Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines