IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Collection et Stream Java Discussion :

Can only iterate over an array or an instance of java.lang.Iterable


Sujet :

Collection et Stream Java

  1. #1
    Membre à l'essai
    Profil pro
    Étudiant
    Inscrit en
    Mai 2007
    Messages
    26
    Détails du profil
    Informations personnelles :
    Localisation : France, Gironde (Aquitaine)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Mai 2007
    Messages : 26
    Points : 22
    Points
    22
    Par défaut Can only iterate over an array or an instance of java.lang.Iterable
    Bonjour,
    Cette erreur est générée dans le servlet dans la méthode findMatches--> String choice : abonne()
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    package fonctions;
     
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Vector;
     
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
     
    import modeles.MdAbonnes;
    import exception.Ca_chie;
     
    /**
     * Servlet implementation class emprunts
     */
    public class emprunts extends HttpServlet {
    	private static final long serialVersionUID = 1L;
     
    	public static final String KEY_VALUE = "value";
        public static final String KEY_DELAY = "delay";
     
        public static final String VAR_LIST = "list";
     
        public static final String VIEW_RESOURCE =
                "/biblio/unordered-list.jsp";
        /**
         * @see HttpServlet#HttpServlet()
         */
        public emprunts() {
            super();
            // TODO Auto-generated constructor stub
        }
     
    	/**
             * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
             */
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		// TODO Auto-generated method stub
    		super.doGet(request, response);
    	}
     
    	/**
             * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
             */
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		// TODO Auto-generated method stub
    		super.doPost(request, response);
    		try{
    		//
            // If a delay was requested, cause the delay to occur
            //
            if (request.getParameter( KEY_DELAY ) != null) {
                delay(request.getParameter( KEY_DELAY ));
            }
            //
            // Get the passed prefix and obtain the list of matches
            //
            String prefix = request.getParameter( KEY_VALUE );
            List<String> matches = findMatches( prefix );
            //
            // Set the matches as a scoped variable on the request
            // and shuffle off to the JSP
            //
            request.setAttribute( VAR_LIST, matches );
            request.getRequestDispatcher( VIEW_RESOURCE  )
                .forward( request, response );}catch(Ca_chie e) {
    				try {
     
     
    					request.setAttribute("message", e.toString());
     
    					getServletContext().getRequestDispatcher("/erreur.jsp").forward(request,response);
     
    				} catch (ServletException e1) {
    					// TODO Auto-generated catch block
    					e1.printStackTrace();
    				} catch (IOException e1) {
    					// TODO Auto-generated catch block
    					e1.printStackTrace();
    				}
    			} catch (ServletException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			} catch (IOException e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		}
     
    	private void delay( String delayValue ) {
            try {
                Thread.sleep( Integer.parseInt( delayValue ) );
            }
            catch (Exception e) {
                //On failure, perform no delay
            }
        }
     
        private List<String> findMatches( String prefix ) throws Ca_chie {
     
     
        	List<String> matches = new ArrayList<String>();
            for (String choice : abonne()) {
                if (choice.startsWith( prefix )) matches.add( choice );
            }
            return matches;
        }
     
        private String abonne() throws Ca_chie{
     
        	MdAbonnes abo= new MdAbonnes();
        	Vector<Vector<String>> vect = new Vector<Vector<String>>();
        	vect.add(abo.affabo());
        	String str = vect.toString();
           	return str;
        }
    }
    Je dois faire en sorte de prendre le Vector<Vector<String>> et de le mettre dans la boite String Choice...
    Pouvez vous m'aider?

  2. #2
    Candidat au Club
    Inscrit en
    Mai 2006
    Messages
    3
    Détails du profil
    Informations forums :
    Inscription : Mai 2006
    Messages : 3
    Points : 3
    Points
    3
    Par défaut
    Bonjour,

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
     
            for (String choice : abonne()) {
                if (choice.startsWith( prefix )) matches.add( choice );
            }
    Si tu utilises cela, ça veut dire que ta méthode "abonne()" te retourne une liste, une collection de String et que tu affectes la valeur de chaque élément de ta liste à ta variable "choice" (à chaque tour de boucle)...

    Donc ton problème se situe dans le fait que ta méthode "abonne()" ne te renvoie qu'un String.

  3. #3
    Membre à l'essai
    Profil pro
    Étudiant
    Inscrit en
    Mai 2007
    Messages
    26
    Détails du profil
    Informations personnelles :
    Localisation : France, Gironde (Aquitaine)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Mai 2007
    Messages : 26
    Points : 22
    Points
    22
    Par défaut
    Merci beaucoup cela m'a aidé à comprendre ce qu'est une list... mais comment convertir mon Vector <Vector<String>> en List <String>?

  4. #4
    Expert éminent sénior
    Avatar de tchize_
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Avril 2007
    Messages
    25 481
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 44
    Localisation : Belgique

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Avril 2007
    Messages : 25 481
    Points : 48 806
    Points
    48 806
    Par défaut
    c'est déjà de nature complètement différente, tu essaie de convertir une collection de collection en une simple collection. Il faut te demander comment tu compte faire çà. Tu veux une liste que regroupe tout? Dans ce cas, tu itère sur la liste des Vector<String> et pour chaque Vector<String> tu itère sur son contenu, donc 2 boucles imbriquées, et tu stocke tout çà dans une nouvelle collection.

    Note: un Vector<Vector<String>> est un structure curieuse. Y a une raison particulière pour avoir utilisé çà plutot qu'un Vector<String> ?

  5. #5
    Membre à l'essai
    Profil pro
    Étudiant
    Inscrit en
    Mai 2007
    Messages
    26
    Détails du profil
    Informations personnelles :
    Localisation : France, Gironde (Aquitaine)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Mai 2007
    Messages : 26
    Points : 22
    Points
    22
    Par défaut
    Oui c'est une structure curieuse que je dois utiliser à mes dépends... C'est pour stocker le ResultSet d'une database...

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    public class Metaresult {
    	private ResultSet resultat;
    	private ResultSetMetaData format;
    	private Statement requete;
    	private conbd plug;
    	private Vector<String> vecolonne = new Vector<String>();
    	private Vector<Vector<String>> vecligne = new Vector<Vector<String>>();
     
     
    	public Metaresult() throws Ca_chie 
    	{
    		plug = new conbd();
    		requete = plug.getStmt();
    	}
     
    	public ResultSet getResultat() {
    		return resultat;
    	}
     
    	public ResultSetMetaData getFormat() {
    		return format;
    	}
     
    	/**
             * @param question
             * @throws Ca_chie
             * @throws SQLException
             * @throws ClassNotFoundException
             */
    	public void execute(String question)
    			throws Ca_chie {
    		try{
     
     
    		if (question.toUpperCase().startsWith("SELECT")) {
    			resultat = requete.executeQuery(question);
    			format = resultat.getMetaData();
    			for (int i = 1; i <= format.getColumnCount(); i++) {
    				vecolonne.add(format.getColumnName(i));
    			}
    			vecligne.add(vecolonne);
    			while (resultat.next()) {
    				vecolonne = new Vector<String>();
    				for (int i = 1; i <= format.getColumnCount(); i++) {
     
    					vecolonne.add(resultat.getString(i));
    				}
    				vecligne.add(vecolonne);
    			}
     
    		} else {
    			if (requete.executeUpdate(question) == 0) {
    				throw new Ca_chie(question);
    			}
    		}
    		}
    		catch(SQLException e){
    			throw new Ca_chie(e);
     
    		}
    	}
    	public void close() throws Ca_chie {
    		try{
    		requete.close();
    		plug.close();
    		}
    		catch(SQLException e){
    			throw new Ca_chie(e);
    		}
    	}
    	public Vector<Vector<String>> getVecligne() {
    		return vecligne;
    	}
    }


    En d'autres termes, je suis obligé d'utilisé ce Vector<Vector<String>> malgré que
    Sun ne privilègie pas l'utilisation des Vector enfin bon... On doit finir l'appli pour
    vendredi donc après c'est fini!! Je me penche sur les deux boucles imbriquées...

    Merci de ton aide!!

  6. #6
    Rédacteur
    Avatar de CyberChouan
    Homme Profil pro
    Directeur technique
    Inscrit en
    Janvier 2007
    Messages
    2 752
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 41
    Localisation : France, Paris (Île de France)

    Informations professionnelles :
    Activité : Directeur technique
    Secteur : Communication - Médias

    Informations forums :
    Inscription : Janvier 2007
    Messages : 2 752
    Points : 4 314
    Points
    4 314
    Par défaut
    Non tu n'es pas "obligé" d'utiliser un Vector de Vector de String... et c'est même déconseillé. Tu devrais plutôt créer un objet métier correspondant à un enregistrement.

    Supposons que ta table Personne aie 3 champs Nom, Prénom, Téléphone. Plutôt que de récupérer un enregistrement sous la forme d'un "Vector de String", tu crées la classe:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    class Personne {
       private String nom;
       private String prenom;
       private String telephone;
     
       // Getters & Setters...
    }
    Et tu récupère un enregistrement en créant une instance de Personne.
    Une requête te renvoyant une liste de plusieurs personnes devient donc en java une List<Personne> (préférable à un Vector<Personne> d'ailleurs).

    Ton code en sera plus clair et beaucoup plus simple à manipuler
    Avant de poster, pensez à regarder la FAQ, les tutoriaux, la Javadoc (de la JRE que vous utilisez) et à faire une recherche
    Je ne réponds pas aux questions techniques par MP: les forums sont faits pour ça
    Mes articles et tutoriaux & Mon blog informatique

  7. #7
    Membre à l'essai
    Profil pro
    Étudiant
    Inscrit en
    Mai 2007
    Messages
    26
    Détails du profil
    Informations personnelles :
    Localisation : France, Gironde (Aquitaine)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Mai 2007
    Messages : 26
    Points : 22
    Points
    22
    Par défaut
    Bonjour,
    nous avons déjà fait çà si j'ai bien compris ce que tu disais dans les modèles...
    Par exemple pour la table abonnes, nous avons:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    package modeles;
     
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.Vector;
     
    import exception.Ca_chie;
    import fonctions.Metaresult;
     
    public class MdAbonnes {
    	protected int id_abonne;
    	protected int id_ville;
    	protected int id_categorie;
    	protected String nom;
    	protected String prenom;
    	protected long date_naissance;
    	protected String adresse;
    	protected String tel_fixe;
    	protected String tel_port;
    	protected String mail;
    	protected int cotisation;
    	protected int etat;
    	protected long date_inscription;
    	private Metaresult meta=null;
     
    	public MdAbonnes() {
     
    	}
     
    	/**
             * @param nom
             * @param prenom
             * @param date_naissance
             * @param adresse
             * @param tel_fixe
             * @param tel_port
             * @param mail
             * @param cotisation smallint
             * @param etat smallint
             * @param date_inscription
             * @param ville
             * @param categorie
             * @throws ClassNotFoundException 
             * @throws SQLException 
             * @throws Ca_chie 
             */
     
     
    	public void ajoute() throws Ca_chie {
     
     
    		String question="INSERT into abonne (nom_abonne,prenom_abonne,date_naiss,adresse_abonne,tel_fixe,tel_port,mail,cotisation,etat,date_inscription,id_ville,id_categorie) values('"+this.nom+"','"+this.prenom+"','"+this.date_naissance+"','"+this.adresse+"', '"+this.tel_fixe+"', '"+this.tel_port+"', '"+this.mail+"', '"+this.cotisation+"', '"+this.etat+"', '"+this.date_inscription+"', '"+this.id_ville+"', '"+this.id_categorie+"')";
    		meta=new Metaresult();
    		meta.execute(question);
    		meta.close();
    	}
     
    	/**
             * @return Tous les abonnes
             * @throws Ca_chie
             * @throws SQLException
             * @throws ClassNotFoundException
             */
    	public Vector<Vector<String>> affiche() throws Ca_chie{
    		String question="SELECT * from abonne;";
    		meta=new Metaresult();
    		meta.execute(question);
    		meta.close();
    		return meta.getVecligne();
    	}
    	public Vector affabo() throws Ca_chie{
    		String question="SELECT nom_abonne from abonne;";
    		meta=new Metaresult();
    		meta.execute(question);
    		meta.close();
    		return meta.getVecligne();
    	}
     
    	public void select() throws Ca_chie{
    		String question="SELECT * from abonne where id_abonne="+this.id_abonne+";";
    		meta=new Metaresult();
    		meta.execute(question);
    		Vector<String> vec=meta.getVecligne().elementAt(1);
    		this.nom=vec.elementAt(1);
    		this.prenom=vec.elementAt(2);
    		this.date_naissance=new Long(vec.elementAt(3));
    		this.adresse=vec.elementAt(4);
    		this.tel_fixe=vec.elementAt(5);
    		this.tel_port=vec.elementAt(6);
    		this.mail=vec.elementAt(7);
    		this.cotisation=new Integer(vec.elementAt(8));
    		this.date_inscription=new Long(vec.elementAt(9));
    		this.etat=new Integer(vec.elementAt(10));
    		this.id_ville=new Integer(vec.elementAt(11));
    		this.id_categorie=new Integer(vec.elementAt(12));
    		meta.close();
     
    	}
     
    	public void select_adresse() throws Ca_chie{
    		String question="SELECT id_abonne from abonne where nom='"+this.nom+"' and prenom='"+this.prenom+"' and adresse='"+this.adresse+"';";
    		meta=new Metaresult();
    		meta.execute(question);
    		this.id_abonne=new Integer(meta.getVecligne().elementAt(1).elementAt(0));
    		meta.close();
    		select();
     
    	}
     
    	public void select_date() throws Ca_chie{
    		String question="SELECT id_abonne from abonne where nom='"+this.nom+"' and prenom='"+this.prenom+"' and date_naiss='"+this.date_naissance+"';";
    		meta=new Metaresult();
    		meta.execute(question);
    		this.id_abonne=new Integer(meta.getVecligne().elementAt(1).elementAt(0));
    		meta.close();
    		select();
     
    	}
     
    	public void modifie() throws Ca_chie{
    		String question="UPDATE abonne set 'nom_abonne'='"+this.nom+"','prenom_abonne'='"+this.prenom+"','date_naiss'='"+this.date_naissance+"','adresse_abonne'='"+this.adresse+"','tel_fixe'='"+this.tel_fixe+"','tel_port'='"+this.tel_port+"','mail'='"+this.mail+"','cotisation'='"+this.cotisation+"','etat'='"+this.etat+"','date_inscription'='"+this.date_inscription+"','id_ville'='"+this.id_ville+"','id_categorie'='"+this.id_categorie+"' where 'id_abonne='"+this.id_abonne+"';";
    		meta= new Metaresult();
    		meta.execute(question);
    		meta.close();
    	}
     
    	public void supprime() throws Ca_chie{
    		String question="DELETE from abonne where id_abonne="+this.id_abonne+";";
    		meta=new Metaresult();
    		meta.execute(question);
    		meta.close();
    	}
     
     
    	public int getId_abonne() {
    		return id_abonne;
    	}
     
    	public void setId_abonne(int id_abonne) {
    		this.id_abonne = id_abonne;
    	}
     
    	public int getId_ville() {
    		return id_ville;
    	}
     
    	public void setId_ville(int id_ville) {
    		this.id_ville = id_ville;
    	}
     
    	public int getId_categorie() {
    		return id_categorie;
    	}
     
    	public void setId_categorie(int id_categorie) {
    		this.id_categorie = id_categorie;
    	}
     
    	public String getNom() {
    		return nom;
    	}
     
    	public void setNom(String nom) {
    		this.nom = nom;
    	}
     
    	public String getPrenom() {
    		return prenom;
    	}
     
    	public void setPrenom(String prenom) {
    		this.prenom = prenom;
    	}
     
    	public long getDate_naissance() {
    		return date_naissance;
    	}
     
    	public void setDate_naissance(long date_naissance) {
    		this.date_naissance = date_naissance;
    	}
     
    	public String getAdresse() {
    		return adresse;
    	}
     
    	public void setAdresse(String adresse) {
    		this.adresse = adresse;
    	}
     
    	public String getTel_fixe() {
    		return tel_fixe;
    	}
     
    	public void setTel_fixe(String tel_fixe) {
    		this.tel_fixe = tel_fixe;
    	}
     
    	public String getTel_port() {
    		return tel_port;
    	}
     
    	public void setTel_port(String tel_port) {
    		this.tel_port = tel_port;
    	}
     
    	public String getMail() {
    		return mail;
    	}
     
    	public void setMail(String mail) {
    		this.mail = mail;
    	}
     
    	public int isCotisation() {
    		return cotisation;
    	}
     
    	public void setCotisation(int cotisation) {
    		this.cotisation = cotisation;
    	}
     
    	public int isEtat() {
    		return etat;
    	}
     
    	public void setEtat(int etat) {
    		this.etat = etat;
    	}
     
    	public long getDate_inscription() {
    		return date_inscription;
    	}
     
    	public void setDate_inscription(long date_inscription) {
    		this.date_inscription = date_inscription;
    	}
    }
    Donc, si je te suis je fais :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    		MdAbonnes abo= new MdAbonnes();
    		List<MdAbonnes> liste;
    Mais comment faire pour avoir une List<String> avec les noms dedans...
    Merci infiniment de votre aide précieuse!

  8. #8
    Membre à l'essai
    Profil pro
    Étudiant
    Inscrit en
    Mai 2007
    Messages
    26
    Détails du profil
    Informations personnelles :
    Localisation : France, Gironde (Aquitaine)

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Mai 2007
    Messages : 26
    Points : 22
    Points
    22
    Par défaut
    Super! j'ai trouvé la réponse...

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    private List<String> abonne() throws Ca_chie{
     
    		List<MdAbonnes> liste= new ArrayList<MdAbonnes>();
    		List<String> lstr= new ArrayList<String>();
    		for (MdAbonnes a : liste)
    		   lstr.add(a.getNom());
     
        return lstr;
     
        }
    Si ça peut aider des gens...

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Réponses: 0
    Dernier message: 27/10/2010, 01h45
  2. [Integration] Jmock et Spring ( et Junit4 !) : can only set expectation on mock object
    Par elix63 dans le forum Spring
    Réponses: 0
    Dernier message: 08/07/2009, 18h07
  3. Réponses: 1
    Dernier message: 11/05/2009, 15h36
  4. Réponses: 1
    Dernier message: 22/04/2009, 16h06
  5. Réponses: 1
    Dernier message: 23/04/2008, 14h52

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo