访问JAVA中父级for循环外的数组

时间:2016-05-29 05:03:12

标签: java arrays for-loop split

我的java应用程序中有这段代码片段。我需要访问parent for循环外的rule_body_arr_l2。我试图在for循环之外初始化数组但在最后一行当我想显示它的值时,它表示数组可能尚未初始化。

String rule_body="person(?x),patientid(?y),haspid(?x,?y)";
     System.out.println(rule_body);
     String rule_body_arr[]=rule_body.split("\\),");
     String rule_body_arr_l2[];
     for(int x=0;x<rule_body_arr.length;x++)
    {
        System.out.println(rule_body_arr[x]);            
        rule_body_arr_l2=rule_body_arr[x].split("\\(");
        System.out.println("LEVEL TWO SPLIT");
        for(int y=0;y<rule_body_arr_l2.length;y++)
        {

            System.out.println(rule_body_arr_l2[y]);

        }

    }
     for(int x=0;x<6;x++)
     {
         System.out.println(rule_body_arr_l2[x]);
     }

此事需要指导

4 个答案:

答案 0 :(得分:1)

如果是,则初始化rule_body_arr_l2,如

String[] rule_body_arr_l2 = new String[YOUR_POSSIBLE_LENGTH];

如果您不确定先前声明中的length字符串,那么最好使用ArrayList<String>

ArrayList<String> rule_body_arr_l2= new ArrayList<String>();

答案 1 :(得分:1)

在Java中,您必须指定数组大小。您尚未创建阵列。你所做的是,你只创建了一个数组引用

默认情况下,在Java中,初始化时所有引用都设置为null。

您必须通过为其提供确切的大小来实例化数组。

例如,

int[] numberArray = new int[5];

答案 2 :(得分:1)

如果我理解您的问题,而不是使用split来解析String,那么您可以使用带有Pattern正则表达式使用类似

的内容解析您的String
String rule_body = "person(?x),patientid(?y),haspid(?x,?y)";
Pattern p = Pattern.compile("person\\((.+)\\),patientid\\((.+)\\),haspid\\((.+)\\)");
Matcher m = p.matcher(rule_body);
if (m.matches()) {
    System.out.printf("person = %s%n", m.group(1));
    System.out.printf("patientid = %s%n", m.group(2));
    System.out.printf("haspid = %s%n", m.group(3));
}

哪个输出

person = ?x
patientid = ?y
haspid = ?x,?y

答案 3 :(得分:0)

尝试拆分),你不会得到逗号问题