简体   繁体   中英

I want to use a variable outside a FOR loop in JAVA

I have a String which I want to use as a parameter in a query. My code is as follows:

List<EventPayload> mylist=eventpojo.getEventPayload();

            for(EventPayload array : mylist)
            {
                System.out.println("Comment Text :"+array.getCommentText());
                System.out.println("Comment Type :"+array.getCommentType());
                System.out.println("Comment Id :"+array.getCommentId());
                System.out.println("Email id :"+array.getComment_email());
                String email1=array.getComment_email();
            }

            EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("jcg-JPA");
            EntityManager em = entityManagerFactory.createEntityManager();

            String email=em.createQuery("SELECT user_id FROM UserInfo WHERE email_id = "+email1).toString();

I want to use String email1 outside the loop in the query.How to implement this??

email1 is inside the forloop so the scope is reduced to that segment...

declaring that outside, will set the scope of the variable to be accessable outside too...

List<EventPayload> mylist=eventpojo.getEventPayload();
String email1=null;  //HERE!!
for(EventPayload array : mylist)
{
    System.out.println("Comment Text :"+array.getCommentText());
    System.out.println("Comment Type :"+array.getCommentType());
    System.out.println("Comment Id :"+array.getCommentId());
    System.out.println("Email id :"+array.getComment_email());
    email1=array.getComment_email();
}

EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("jcg-JPA");
EntityManager em = entityManagerFactory.createEntityManager();

String email=em.createQuery("SELECT user_id FROM UserInfo WHERE email_id = "+email1).toString();

short answer: you can't

long answer/further question: What do you want to to?

Fire a SQL for each EventPayload -> then do this in the loop

Fire a SQL for one distinct EventPayload -> look in the list for the object (or filter the list) and execute the query for this object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM