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
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
Título: Re: Duda Arraylist Publicado por: Nasty35 en 15 Mayo 2014, 17:23 pm Prueba con:
Código
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
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 Esta iniciado en el constructor Sería de ayuda que posteases todo el código, a ciegas es muy difícil.Código
pd: el codigo anterior da el error de: The constructor DirectoryItem (int,String) is undefined 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 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
Título: Re: Duda Arraylist Publicado por: betikano en 17 Mayo 2014, 20:36 pm Código
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
Título: Re: Duda Arraylist Publicado por: betikano en 17 Mayo 2014, 21:27 pm ¿Así funciona? Código
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
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 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
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.- |