accessing array outside the parent for loop in JAVA - java

i have this code snippet in my java application. i need to access the rule_body_arr_l2 outside the parent for loop. i tried to initialize the array outside the for loop but in the last line when i want to display its value, it says the array might not have been initialized yet.
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]);
}
Guidance is required in the matter

In Java, you must specify the array size. You haven't created an array. What you have done is, you have only created an array reference.
By default, in Java all references are set to null when initializing.
You must instantiate an array by giving an exact size for it.
For example,
int[] numberArray = new int[5];

If I understand your question, rather than using a split to parse the String you could use a regular expression with a Pattern to parse your String with something like
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));
}
Which outputs
person = ?x
patientid = ?y
haspid = ?x,?y

If so then initialize rule_body_arr_l2 like
String[] rule_body_arr_l2 = new String[YOUR_POSSIBLE_LENGTH];
If you are not sure the length of String in prior declaration then better using ArrayList<String> like
ArrayList<String> rule_body_arr_l2= new ArrayList<String>();

try splitting at ), u wont get the comma problem

Related

how to check contains in arraylist or set

I have two Strings
String first = "value=[ABC,PQR,XYZ]"
String second="value=[ABC]"
I am trying to check the contains of string second into a string first.
I am using the below code
List<String> list = new Arraylist<>();
list.add(first);
if(list.contains(second)){
// do something
}
How to check contains in the list which has string with multiple ","?
Which data structure should I use for above problem?
Probably, you don't know how to work with lists in java...
In your case, you are adding a string "value=[ABC,PQR,XYZ]" to the list. Hence, you have a list with only one item.
If you want to create such a list ["ABC","PQR","XYZ"], you have to add these three elements one by one.
P.S. If you studied java basic, you wouldn't have such problems...
String first = "value=[ABC,PQR,XYZ]";
String second ="value=[ABC]";
String secondVal = second.substring(second.indexOf("[") + 1, second.indexOf("]"));
String[] firstArry = first.substring(first.indexOf("[") + 1, first.indexOf("]")).split(",");
boolean secondInFirst = false;
for (int i = 0; i < firstArry.length; i++) {
if (firstArry[i].equals(secondVal)) {
secondInFirst = true;
break;
}
}
I'm not sure why the first and second are formatted in such a way, however, assuming they are always formatted the same way ("value=[X,Y,Z]"),
We must break first up into a fixed list ("value=[ABC,PQR,XYZ]" -> {"ABC","PQR","XYZ"})
Format second to be readable ("value=[ABC]" -> "ABC")
Loop through firstArry and find matches
Store the result in secondInFirst

Can not sort out how the Array is updated

Hi i have this code of work from some one, its working fine as intended and i come to the point that this particular code is updating the value of temp[][]. but i can not figure our exaxtly where the temp[i][j]=updated is working out.
as the method is not returning any thing, and there is no assigning to temp[][]. all i see is the update_table[][]=temp;
when i try to print the temp before the loop and after the loop there is change in the array.
void var_init(String to_match_x,String to_match_y, String to_replace_x, String to_replace_y,String[][] temp)
{
String t_match_x=to_match_x;
String t_replace_x=to_replace_x;
String t_match_y=to_match_y;
String t_replace_y=to_replace_y;
//String str=string;
//add function to count variables find duplicates and assign values to them
line();
System.out.println("text to match:"+t_match_x);
System.out.println("text to replace with:"+t_replace_x);
System.out.println("text to match:"+t_match_y);
System.out.println("text to replace with:"+t_replace_y);
String[][] table_update=temp;
line();
System.out.println("starting fetching rules for updating variable");
line();
for(int i=0;i<table_update.length;i++)
for(int j=0;j<table_update[0].length;j++)
{
String replace_text=table_update[i][j];
System.out.println(replace_text);
String new_str;
new_str=replace_text.replaceAll("\\"+t_match_y,t_replace_y);
new_str=new_str.replaceAll("\\"+t_match_x,t_replace_x);
table_update[i][j]=new_str;
System.out.println(table_update[i][j]);
line();
}
}
you are reffering to an array called temp
String[][] table_update=temp;
once you update table_update array temp will also be updated.if you dont want that to happen make a clone of temp array like this
String[][] table_update = temp.clone();
String[][] table_update=temp;
This means that table_update and temp both have the same reference, so actually they are both the same array if one of them is updated its expected to the other one to be updated also.
You can create a new array (temp) and clone table_update to it that would solve your issue.

Two dimensional string array in java

I am new to java please help me with this issue.
I have a string lets say
adc|def|efg||hij|lmn|opq
now i split this string and store it in an array using
String output[] = stringname.split("||");
now i again need to split that based on '|'
and i need something like
arr[1][]=adc,arr[2][]=def and so on so that i can access each and every element.
something like a 2 dimensional string array.
I heard this could be done using Arraylist, but i am not able to figure it out.
Please help.
Here is your solution except names[0][0]="adc", names[0][1]="def" and so on:
String str = "adc|def|efg||hij|lmn|opq";
String[] obj = str.split("\\|\\|");
int i=0;
String[][] names = new String[obj.length][];
for(String temp:obj){
names[i++]=temp.split("\\|");
}
List<String[]> yourList = Arrays.asList(names);// yourList will be 2D arraylist.
System.out.println(yourList.get(0)[0]); // This will print adc.
System.out.println(yourList.get(0)[1]); // This will print def.
System.out.println(yourList.get(0)[2]); // This will print efg.
// Similarly you can fetch other elements by yourList.get(1)[index]
What you can do is:
String str[]="adc|def|efg||hij|lmn|opq".split("||");
String str2[]=str[0].split("|");
str2 will be containing abc, def , efg
// arrays have toList() method like:
Arrays.asList(any_array);
Can hardly understand your problem...
I guess you may want to use a 2-dimenison ArrayList : ArrayList<ArrayList<String>>
String input = "adc|def|efg||hij|lmn|opq";
ArrayList<ArrayList<String>> res = new ArrayList<ArrayList<String>>();
for(String strs:input.split("||")){
ArrayList<String> strList = new ArrayList<String>();
for(String str:strs.split("|"))
strList.add(str);
res.add(strList);
}

Naming Arraylists in a loop - Java

I need to create an Arraylist in a while loop with a name based on variables also in the loop. Here's what I have:
while(myScanner.hasNextInt()){
int truster = myScanner.nextInt();
int trustee = myScanner.nextInt();
int i = 1;
String j = Integer.toString(i);
String listname = truster + j;
if(listname.isEmpty()) {
ArrayList listname = new ArrayList();
} else {}
listname.add(truster);
i++;
}
The variable truster will show up more than once while being scanned, so the if statement is attempting to check if the arraylist already exists. I think I might have done that out of order, though.
Thanks for your help!
Store the ArrayLists in a Map:
Map<String, List<String> listMap = new HashMap<String,List<String>>();
while (myScanner.hasNextInt()){
// Stuff
List<String> list = new ArrayList<String>();
list.add(truster);
listMap.put(listname, list);
}
Note the use of generics (the bits in <>) to define the type of Object the List and Map can contain.
You can access the values stored in the Map using listMap.get(listname);
If I understand you correctly, create a list of lists or, better yet, create a map in which the key is the dynamic name you want and the value is the newly created list. Wrap this in another method and call it like createNewList("name").
Really not sure what you mean at all but you have some serious fundamental flaws with your code so I'll address those.
//We can define variables outside a while loop
//and use those inside the loop so lets do that
Map trusterMap = new HashMap<String,ArrayList<String>>();
//i is not a "good" variable name,
//since it doesn't explain it's purpose
Int count = 0;
while(myScanner.hasNextInt()) {
//Get the truster and trustee
Int truster = myScanner.nextInt();
Int trustee = myScanner.nextInt();
//Originally you had:
// String listname = truster + i;
//I assume you meant something else here
//since the listname variable is already used
//Add the truster concated with the count to the array
//Note: when using + if the left element is a string
//then the right element will get autoboxed to a string
//Having read your comments using a HashMap is the best way to do this.
ArrayList<String> listname = new ArrayList<String>();
listname.add(truster);
trusterMap.put(truster + count, listname);
i++;
}
Further, you are storing in myScanner a stream of Ints that will get fed in to the array, but which each have very different meanings (truster and trustee). Are you trying to read these in from a file, or user input? There are better ways of handling this and if you comment below with what you mean I'll update with a suggested solution.

Regarding arrayList

I have used scanner instead of string tokenizer ,, below is the piece of code...
Scanner scanner = new Scanner("Home,1;Cell,2;Work,3");
scanner.useDelimiter(";");
while (scanner.hasNext()) {
// System.out.println(scanner.next());
String phoneDtls = scanner.next();
// System.out.println(phoneDtls);
ArrayList<String> phoneTypeList = new ArrayList<String>();
if(phoneDtls.indexOf(',')!=-1) {
String value = phoneDtls.substring(0, phoneDtls.indexOf(','));
phoneTypeList.add(value);
}
Iterator itr=phoneTypeList.iterator();
while(itr.hasNext())
System.out.println(itr.next());
}
The ouput I get upon executing this...
Home
Cell
Work
As it is seen from the above code is that in the array list phoneTypeList we are finally storing the values..but the logic of finding out the value on the basisi of ',' is not that much great..that is ..
if(phoneDtls.indexOf(',')!=-1) {
String value = phoneDtls.substring(0, phoneDtls.indexOf(','));
phoneTypeList.add(value);
}
could you please advise me with some other alternative ..!! to achieve the same thing...!!thanks a lot in advance..!!
Well, since you asked if there is another way to do it then here is an alternative: You can split the string directly and do it with less code with the foreach statement:
String input = "Home,1;Cell,2;Work,3";
String[] splitInput = input.split(";");
for (String s : splitInput ) {
System.out.println(s.split(",")[0]);
}
No need to use the ArrayList<T> since you can iterate over an array as well.
could you try to split based on ',' STIRNG_VALUE.split(','); will return u an array with strings separated with , may be this helps
If i understand correctly. The problem statement is you want to maintain a list of Phone-Type-List. Like this: ["Home", "Cell", "Work"].
I suggest you keep this in a property file / config file / database which ever makes sense and load it to memory on start of you app.
If the input cannot be changed then as for the algorithm i couldn't think of a better one. Looks good.
You could use split function of string if that makes sense.
First use split on ";"
Then a split on ","
declare the arraylist outside the while loop.
try this, i have made some change for better performance too. hope you can compare and understand the change.
ArrayList<String> phoneTypeList = new ArrayList<String>();
Scanner scanner = new Scanner("Home,1;Cell,2;Work,3");
scanner.useDelimiter(";");
String phoneDtls = null;
String value = null;
while (scanner.hasNext()) {
phoneDtls = scanner.next();
if (phoneDtls.indexOf(',') != -1) {
value = phoneDtls.split(",")[0];
phoneTypeList.add(value);
}
}
Iterator itr = phoneTypeList.iterator();
while (itr.hasNext())
System.out.println(itr.next());
I have executed n got the result, check screenshot.

Categories