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.
Related
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
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 2 years ago.
I'm fairly new to java and I believe the problem comes from my lack of understanding.
I am trying to read an Array List of CSV values. Below is my code:
public static void readFile(){
String line = "";
try{
BufferedReader br = new BufferedReader(new FileReader(Main.filepath));
while((line = br.readLine()) != null){ //reads whilst the next line is not null
fileData.add(line); //adds current line to array list
}
catch (Exception ex){
System.out.println("File Not Found"); //if file not found, print
}
}
public class Film{
public static void duration(){
readFile();
for (int i = 0; i < (fileData.size()); i++) {
//System.out.println(fileData);
String[] temp = fileData.get(1).split(",");
System.out.println(temp);
}
}
readFile() reads the CSV file and saves each line as an element in an ArrayList
filedata is the ArrayList
filepath is the path to the file
The CSV file is in format "filmName,releaseDate,filmRating,filmGenre,filmDuration,filmScore"
I'm trying to get Film() to print out the release dates of every element in the ArrayList, however my output is:
[Ljava.lang.String;#6bf2d08e
[Ljava.lang.String;#5eb5c224
[Ljava.lang.String;#53e25b76
[Ljava.lang.String;#73a8dfcc
When I'm expecting something more like
1999
2007
1956
1987
Any help is appreciated.
Iterate over each String of the array tmp and print that value. Moreover, you should replace fileData.get(1).split(","); for fileData.get(i).split(",");
for (int i = 0; i < (fileData.size()); i++) {
String[] tmp = fileData.get(i).split(",");
for(String t : tmp)
System.out.println(tmp);
}
If you System.out.println(); the array you will be printing basically, each String hashcode. Alternatively, you can use Arrays.toString to print the entire array in one go:
for (String fileDatum : fileData) {
String[] tmp = fileDatum.split(",");
System.out.println(Arrays.toString(tmp));
}
Finally, you use Streams from Java you can simplify your method to only:
fileData.stream().map(i -> i.split(",")).forEach(i -> Arrays.asList(i).forEach(System.out::println));
or with a different formatting style:
fileData.stream().map(i -> i.split(",")).map(Arrays::toString).forEach(System.out::println);
String[] temp = fileData.get(1).split(",");
System.out.println(temp);
This prints out the Array with the default implementation of toString:
Returns a string representation of the object. In general, the
toString method returns a string that "textually represents" this
object. The result should be a concise but informative representation
that is easy for a person to read. It is recommended that all
subclasses override this method.
The toString method for class Object returns a string consisting of
the name of the class of which the object is an instance, the at-sign
character `#', and the unsigned hexadecimal representation of the hash
code of the object. In other words, this method returns a string equal
to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
In your case you need to iterate over the Array again and spring each element with toString
You have to first reefer to i variable instead of 1 in your loop, then the split method returns an array of String, so you should select the correct value in the array :
String[] temp = fileData.get(i).split(",");
System.out.println(temp[1]);
This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 6 years ago.
Okay so I have this two Lists called idadults and adults, I also have two String[] arrays called infoAdults (of size 255) and adultsID (of size 1). The code I have makes infoAdults read the information from a CSV file and adds that information to the adults list. It also checks if any value/box is missing, and changes its value to "9999". On column #15 in the CSV file, there's the id of each Adult, but some of them are missing. adultsID grabs each value of the column and then adds it to the idadults list. The code also first checks if that value exists, and if not it changes it to "9999" again.
My problem is that when I print the adults list it prints everything correctly like it should be, but when I try to print the idadults list it only prints the last value in the column over and over again n times, n being the size of the column. I already tried removing the "static" part when I define both of my Lists, but it didn't work. I also already tried to print adultsID[0] individually, and they all print correctly.
What do?
public String[] adultsID = new String[1];
public static List<String[]> idadults = new ArrayList<String[]>();
public static String csvFile = userDir + "/Adults.csv";
public String[] infoAdults = new String[255];
public static List<String[]> adults = new ArrayList<String[]>();
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
infoAdults = line.split(csvSplitBy);
for(int i=0;i<infoAdults.length;i++){
if(infoAdults[i].isEmpty()){
infoAdults[i]="9999";
}
if(i>16){
adultsID[0]=infoAdults[16];
}
else{
adultsID[0]="9999";
}
}
idadults.add(adultsID);
adults.add(infoAdults);
}
for (String[] strings : idadults) {
System.out.println(Arrays.toString(strings));
}
}
When you add adultsID to adults, you are adding the reference of adultsID.
Inside the while loop you are modifying only the data referenced by adultsID:
if(i>16){
adultsID[0]=infoAdults[16];
}
else{
adultsID[0]="9999";
}
And then you are adding the same reference to adults, on every iteration
idadults.add(adultsID);
So all the references point to same data which is modified every time the loop runs.
That is why you see only the last value reflected in all the list elements.
But for infoAdults , you are reassigning a new array to infoAdults everytime in the loop:
infoAdults = line.split(csvSplitBy);
So infoAdults refers to new data on every iteration.
Thus you add a new instance of infoAdults everytime in the list and all of them refer to different data
To get the expected output you can assign a new array to adultsID everytime in loop:
while ((line = br.readLine()) != null) {
infoAdults = line.split(csvSplitBy);
adultsID = new String[500];
for(int i=0;i<infoAdults.length;i++){
if(infoAdults[i].isEmpty()){
infoAdults[i]="9999";
}
if(i>16){
adultsID[0]=infoAdults[16];
}
else{
adultsID[0]="9999";
}
}
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
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.