I have 2 arraylists. I am using one arraylist as a key to store values.
In nutshell, my code is as below.
for(int i=0;i<transactionid.size(); i++)
{
if(transactionid.get(i).equals(transactionnumber))
{
transactionvalue.set(i, transactionvalues);
}
}
In the above program snippet, transactionid is used to store my key values. If there is a match in the key value, I am updating the arraylist transactionvalue.
So far so good. But now, I want to update another arraylist diskitemvalues based on the above two arraylist values. The update is something like below.
for(int i=0;i<transactionid.size(); i++)
{
if(transactionid.get(i).equals(transactionnumber))
{
try
{
/* Open file to read contents*/
while ((strLine = br.readLine()) != null)
{
/* Get the values of transactionvalue arraylist and update them. */
/* The transactionvalue arraylist contains values like {X Y} */
/* So my update in the diskitemvalues arraylist
should be X = so & so Y = so & so based on file */
I have to navigate to the particular value in the transactionid arraylist and for that particular key, I have to find out the corresponding values in the transactionvalue arraylist and update the diskitemvalues arraylist for all values present in the transactionvalue arraylist.
Example:
Transactionid transactionvalue
1 X Y
2 M N
For transactionid = 2, my diskitemvalues [2] should have M = so & so and N = so & so from the input file. If it is transactionid = 1, my diskitemvalues[1] should have X = so & so and Y = so & so from the input file.
Related
Hi i'm trying to loop through this structure:
id string1 string2 different_string
1 test test asd
1 test test dsa
2 data data qwe
3 info info ewq
3 info info zxc
3 info info qaz
I have rows with the exact same value but one of them is different so I'm trying to compress that data into a single row.
This is my code:
int actual_id = list.get(0).num(); //I pick the first id = 1
ArrayList<ArrayList<String>> listOLists = new ArrayList<ArrayList<String>>();
ArrayList<String> items = new ArrayList<String>();
for(int i = 0; i < list.size(); i++){
if(list.get(i).id == actual_id){
String str = list.get(i).different_string;
items.add(str);
listOLists.add(items);
items.clear();
}else {
actual_id = list.get(i).id;
i--;
}
}
for(int j = 0; j < listOLists.size(); j++) {
System.out.println(listOLists);
}
First I check the id of each row and compare it with the actual value, I'm adding the string to an array and then append it to a list so I can store my data then reset the array to append new data to it and repeat the process, the problem is when I reset the array the loop doesn't seem to add more items to the list, what am I doing wrong?
this is I would like to get something like this:
{1, test, test, {asd, dsa}},{2, data, data, {asd}},{3, info, info, {ewq, zxc,qaz}}
Your code is a little difficult to follow but from what I can tell, your problem lies in this part of the code:
if(list.get(i).id == actual_id){
String str = list.get(i).different_string;
items.add(str);
listOLists.add(items);
items.clear();
}else {
You add items to listOList, but in the next line you clear it. items still refers to the List you just added to listOList so when you clear it, it clears the list in listOList as well. You may want to declare items within the if block so a new List will be created each pass through the loop like this:
if(list.get(i).id == actual_id){
ArrayList<String> items = new ArrayList<String>();
String str = list.get(i).different_string;
items.add(str);
listOLists.add(items);
}else {
This way, a new List is being created every iteration through the loop avoiding the issue. I can't tell if this will solve all you're problems but I hope this gets you headed in the right direction.
I have a master arraylist call toBeDeleted which stored timestamp and email. The following are the sample data inside the toBeDeleted arraylist
[1507075234, bunny#outlook.com]
I have one arraylist call logData1 which stored status,email,timestamps and ID. The following are the sample data inside the logData1 arraylist.
[16, bunny#outlook, 1507075234, 0OX9VQB-01-00P-02]
I hope to delete the data inside the logData1 arraylist by verifying the timestamp first with timestamps stated in toBeDeleted1 arraylist, if the timestamp matched, I will check the email for both arraylist. If both of them are matched, I would like to delete away all the data (status,email,timestamp,ID). But I cant make it work
this is my sample output from my source code
[16, bunny#outlook.com, 1507075234, 0OX9VQB-01-00P-02]
The data inside toBeDeleted1 is :[1507075234, bunny#outlook.com]
The time1 is :1507075234
The email1 is :bunny#outlook.com
The time is :1507075234
The emails is :bunny#outlook.com
The data is :bunny#outlook.com
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -3
at java.util.ArrayList.elementData(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at EmailReporting.main(EmailReporting.java:83)
This is my sample program
System.out.println(logData1);
System.out.println("The data inside toBeDeleted1 is :"+toBeDeleted1);
for(int v = 0;v<toBeDeleted1.size();v++) //look through the logdata1 for removing the record base on timestamp
{
String time1 = toBeDeleted1.get(v);
String email1 = toBeDeleted1.get(v+1);
System.out.println("The time1 is :"+time1);
System.out.println("The email1 is :"+email1);
for(int f = logData1.size();f>logData1.size()-1;f--)
{
// System.out.println(logData1.size());
// System.out.println("The data in logdata1 is "+logData1.get(f-2));
if(time1.equals(logData1.get(f-2)))
{
System.out.println("The time is :"+logData1.get(f-2));
System.out.println("The emails is :"+logData1.get(f-3));
if(email1.equals(logData1.get(f-3)))
{
System.out.println("The data is :"+logData1.get(f-3));
logData1.remove(f-1);
logData1.remove(f-2);
logData1.remove(f-3);
logData1.remove(f-4);
f-=4;
}
}
}
}
The error occurred after this line of code executed
System.out.println("The data is :"+logData1.get(f-3));
You can find elements in the list in order using Collections.indexOfSubList:
List<String> toFind = Arrays.asList(time1, email1);
int emailIndex = Collections.indexOfSubList(logData1, toFind);
A similar lastIndexOfSubList method also exists. That might be more appropriate for your use case.
You can then use this to remove the elements from toFind:
int emailIndex = Collections.lastIndexOfSubList(logData1, toFind);
if (emailIndex >= 1) {
logData1.subList(emailIndex-1, emailIndex+3).clear();
}
Just do this in a loop to keep going until all occurrences have been removed.
Note that just doing this in a loop naively will keep on searching over the tail of the list repeatedly. Instead, you can use subList to "chop" the end of the list, to avoid re-searching it:
List<String> view = logData1;
int emailIndex;
while ((emailIndex = Collections.lastIndexOfSubList(view, toFind)) >= 1) {
logData1.subList(emailIndex-1, emailIndex+3).clear();
view = logData1.subList(0, emailIndex-1);
}
Additionally, note that deleting from the middle of an ArrayList is inefficient, because the elements after the ones you delete have to be shifted down. This is why using subList(...).clear() is better, because it does all of those shifts at once. But if you are removing lots of 4-element batches, you can do better.
Instead of the subList(...).clear(), you can set the bits of elements to be deleted into a BitSet:
List<String> view = logData1;
BitSet bits = new BitSet(logData1.size());
int emailIndex;
while ((emailIndex = Collections.lastIndexOfSubList(view, toFind)) >= 1) {
bits.set(emailIndex-1, emailIndex+3);
view = logData1.subList(0, emailIndex-1);
}
And then shift all the elements down at once, discarding the elements you want to delete:
int dst = 0;
for (int src = 0; src < logData1.size(); ++src) {
if (!bits.get(src)) {
logData1.set(dst++, logData1.get(src));
}
}
And now truncate the list:
logData1.subList(dst, logData1.size());
so I am new to programming and having some issues with classes. I am using the lens next brick. There is a class from the libuary called Node. It takes a X and Y. Like so:
Node nodeNameOne = new Node(2,3);
What I want to do:
I have a 12 by 12 array. And for each position in the array I want to get its X and Y and create a new node. The problem is I want to automatically change the " nodeNameOne" .
My solution was to create a intiger variable and increment it, then do a .to string and use that as the nodes name by when I use my intiger variable name it uses the name of the variable not the value within the variable.
I have looked at other posts that sujest using "Class.newInstance" but I can't get this to work.
Any help is appreciated.
Thanks
UPDATE:
I have a 12 by 12 array. I will scan the array and when I detect a 0 in any position of the array i want to create a new Node with the X and Y of the array position.
because it is a 12 by 12 array there are 144 possible places that 0 can occur.
therefore the code that is needed to make a new is node is:
Node nodename = new Node(x,y);
I want to automate the instance name: "nodeName" to use a string variable, that I will get from:
int nameOfNode= 0;
String temp = Integer.toString(nameOfNode);
Node temp = new Node(x,y);
nameOfNode++;
the error i get is that it says that temp is already used, but i know that. i want it to use the value of temp not the name "temp". - i hope this is clearer.
What you want is probably an array. A twodimensional array is a mapping from (i,j) --> Node[i][j]:
// Step 1 and 2: Create and add nodes
Node nodes[12][12];
for (int i = 0; i < 12; i++) {
for (int j = 0; j < 12; j++) {
nodes[i][j] = new Node(i, j);
mesh.add(nodes[i][j], 0);
}
}
You can then refer to a node by using numbers (or integer variables):
// Step 3: Connect nodes:
mesh.connect(nodes[2][3], nodes[2][4]);
mesh.connect(nodes[2][3], nodes[3][3]);
mesh.connect(nodes[2][4], nodes[2][5]);
...
I think you want a java.util.Map;
A Maps is an object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value. You can use Strings "x,y" as keys for your nodes objects then you can retrieve your node objects by strings the way you want.
you can use an map like this:
final Map<String,Node> nodesMapedByName = new HashMap<>();
(...)
//asssuming x and y are integers, this will create an
//new node for x and y and put it in the map using the string
//"x,y" as key
nodesMapedByName.put(x + "," + y, new Node(x,y);
(...)
//asssuming x and y are integers, this will retrieve the node
//mapped by the String "x,y"
final Node someNome = nodesMapedByName.get(x + "," + y);
I have created a list of 2D arrays containing randomly generated number values for different locations.
public static int Prices[][] = new int[Cities.length][ItemNames.length];
public static List<int[][]> CityPrices = new ArrayList<int[][]>();
public static void NewDay()
{
for(int i = 0; i<Cities.length; ++i)
{
Prices[i] = PriceGenerator.ReturnPricesForCity(i);
//This method returns an array of random integers
}
CityPrices.add(Prices);
}
But then later when I want to retrieve the price history for a specific item for the amount of days passed, it returns the same value for each day
int Prices[] = new int[GlobalVariables.CityPrices.size()];
String sTest = "";
for(int i = 0; i < Prices.length; ++i)
{
Prices[i] = GlobalVariables.CityPrices.get(i)[spinCity.getSelectedItemPosition()][spinItem.getSelectedItemPosition()];
sTest = sTest + Prices[i] + ",";
}
In this case, the values returned by sTest was : 6055,6055,6055,6055,6055, for five consecutive days.
If I would for instance add a day, the values would change to a range of a new number, which in this case was : 7294,7294,7294,7294,7294,7294,
Please show me what I am doing wrong, as I have been trying to figure this one out the past 4 days with no luck.
Every element in your CityPrices list is the same: in each case, you are adding the Prices two-dimensional array. Your loop modifies Prices[i], but it doesn't change Prices, which is still a reference to the same two-dimensional array right the way through.
I think you're imagining it will pass the contents of the array in its current state, but it doesn't: it passes a reference to the array to the .add() method, so any subsequent changes to the array will be reflected in the contents of CityPrices.
If at the end of your loop you try
CityPrices.get(0) == CityPrices.get(1)
you'll see it returns true.
In the assignment: Prices[i] = GlobalVariables.CityPrices.get(i)[spinCity.getSelectedItemPosition()][spinItem.getSelectedItemPosition()]; you are basically referencing an int[][] at the same index for both dimensions.
On top of that, the spinCity.getSelectedItemPosition() invocation might be returning the same index at every iteration of your loop, hence your identical values.
It's hard to assume anything further as you haven't posted the code for spinCity.
I'm attempting to use DOCX4J to parse and insert content into a template. As part of this template I have loops which I need to copy everything inbetween two markers, and repeat all that content X times.
The relavant code is as follows:
public List<Object> getBetweenLoop(String name){
String startTag = this.tag_start + name + "_LOOP" + this.tag_end;
String endTag = this.tag_start + name + this.tag_end;
P begin_loop = this.getTagParagraph(startTag);
P end_loop = this.getTagParagraph(endTag);
ContentAccessor parent = (ContentAccessor) this.getCommonParent(begin_loop, end_loop);
List<Object> loop = new ArrayList<Object>();
boolean save = false;
//Cycle through the content for the parent and copy all the objects that
//are between and including the start and end-tags
for(Object item : parent.getContent()){
if(item.equals(begin_loop) || item.equals(end_loop))
save = (save) ? false : true;
if(save || item.equals(end_loop)){
loop.add(XmlUtils.deepCopy(item));
}
if(item.equals(end_loop)){
//Here I want to insert everything copied X times after the current item and then exit the for loop.
//This is the part I'm not sure how to do since I don't see any methods "Insert Child", etc.
}
}
return loop;
}
getTagParagraph successfully returns the object representing the paragraph for the tag sent. This works beautifully.
getCommonParent returns the shared parent between the two supplied tags. This works beautifully.
My problem is, as commented, how to insert the newly copied items into the appropriate place.
If you're looking to insert all the objects you have stored in your loop collection, you simply need to do something like this (in the conditional you've commented):
item.getContent().addAll(loop);
item represents the end_loop object (a paragraph or whatever), and inserts all the objects you've collected into the loop collection. (addAll may require an int argument too, I can't recall, but if it does that's just the desired index within the overall MainDocumentPart.getContent() JAXB document representation).
#Ben, thank-you!
If you know of any instances where below wouldn't work, please let me know.
I had actually just figured out something very similar, but ended up changing a lot more code. Below is what I put together.
public void repeatLoop(String startTag, String endTag, Integer iterations){
P begin_loop = this.getTagParagraph(startTag);
P end_loop = this.getTagParagraph(endTag);
ContentAccessor parent = (ContentAccessor) this.getCommonParent(begin_loop, end_loop);
List<Object> content = parent.getContent();
Integer begin_pointer = content.indexOf(begin_loop);
Integer end_pointer = content.indexOf(end_loop);
List<Object> loop = new ArrayList<Object>();
for(int x=begin_pointer; x <= end_pointer; x = x + 1){
loop.add(XmlUtils.deepCopy(content.get(x)));
}
Integer insert = end_pointer + 1;
for(int z = 1; z < iterations; z = z + 1){
content.addAll(insert, loop);
insert = insert + loop.size();
}
}