简体   繁体   English

我想在 JAVA 的 FOR 循环之外使用一个变量

[英]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??我想在查询的循环外使用 String email1。如何实现?

email1 is inside the forloop so the scope is reduced to that segment... email1在 forloop 内,因此范围缩小到该段...

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为每个 EventPayload 触发 SQL -> 然后在循环中执行此操作

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为一个不同的 EventPayload 触发 SQL -> 在列表中查找对象(或过滤列表)并执行此对象的查询

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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