How can I access objects in a loop? - java

I am trying to hand over the position value of my object 'next' to the next 'next' object. Is it possible to write this code as a loop and scale it by n?
next.next.next.next.pos.y = next.next.next.pos.y;
next.next.next.next.pos.x = next.next.next.pos.x;
next.next.next.pos.y = next.next.pos.y;
next.next.next.pos.x = next.next.pos.x;
next.next.pos.y = next.pos.y;
next.next.pos.x = next.pos.x;
next.pos.x = pos.x;
next.pos.y = pos.y;

I guess you want something like this:
while(obj.next != null) {
obj.next.pos.x = obj.pos.x;
obj.next.pos.y = obj.pos.y;
obj = obj.next;
}
Later edit:
Sorry, I misunderstood your question.
You could then use a list to solve this issue. It's not the most performant way to do it but I will work.
List<Obj> objs = new ArrayList<>();
objs.add(obj);
// Add everything to a list
while(obj.next != null) {
objs.add(obj.next);
obj = obj.next;
}
// Walk the list in the reverse order
for(i = objs.size() - 1; i > 1 ; i--) {
objs[i].pos.x = objs[i - 1].pos.x;
objs[i].pos.y = objs[i - 1].pos.y;
}

Related

NPE occurs when add an object in Array of ArrayList

How do I resolve this problem...
I wanna add object OrgDO in allOrgListArr[idx].
ArrayList<OrgDO>[] allOrgListArr = new ArrayList[Integer.parseInt(maxLv)+1];
for(int i = 0; i < Integer.parseInt(maxLv)+1; i++) {
allOrgListArr[i] = new ArrayList<OrgDO>();
}
for(OrgDO org : allOrgList.getOrgListList()) {
allOrgListArr[org.getORG_LEVEL()].add(org); // --> this part throws a NullPointerException
}
You need to be a bit more defensive in your programming and check that the index exists in the array and if so you also need to check that you have an object at that index
for(OrgDO org : allOrgList.getOrgListList()) {
int level = org.getORG_LEVEL();
if (level >= allOrgListArr.length()) {
continue; //or other error handling
}
List<OrgDO> list = allOrgListArr[level];
if (list == null) {
list = new ArrayList<OrgDO>();
allOrgListArr[level] = list;
}
list.add(org);
}

Convert array of Strings to Array list

I have a String array with name and id, I need to convert that String array to List of objects.
This is my code:
private List<ObjectAttribute> getDtls(String newVal) {
ObjectAttribute object = new ObjectAttribute();
List<ObjectAttribute> objLst = new ArrayList<ObjectAttribute>();
String[] newImageVal = [step0005.jpg, 172B6846-0073-4E5B-B10A-DDD928994EA6, step0003.jpg, FBC8D143-2CD7-47E6-B323-31A0928A9338]
for (int i = 0; i <= newImageVal.length - 1; i++) {
object.setImageName(newImageVal[i]);
object.setImageId(newImageVal[++i]);
objLst.add(object);
}
return objLst;
}
but there is a problem that it always returns only the last value in objList. Can anyone correct this code.
move
ObjectAttribute object = new ObjectAttribute();
inside the for loop:
for (int i = 0; i <= newImageVal.length - 1; i++) {
ObjectAttribute object = new ObjectAttribute();
object.setImageName(newImageVal[i]);
object.setImageId(newImageVal[++i]);
objLst.add(object);
}
private List<ObjectAttribute> getDtls(String newVal) {
List<ObjectAttribute> objLst = new ArrayList<ObjectAttribute>();
String[] newImageVal = [step0005.jpg, 172B6846-0073-4E5B-B10A-DDD928994EA6, step0003.jpg, FBC8D143-2CD7-47E6-B323-31A0928A9338]
// String delimiter = ", ";
// newImageVal = newVal.split(delimiter);
for (int i = 0; i <= newImageVal.length - 1; i++) {
ObjectAttribute object = new ObjectAttribute();
object.setImageName(newImageVal[i]);
object.setImageId(newImageVal[++i]);
objLst.add(object);
}
return objLst;
}
The root cause of your problem is, as #StefanBeike wrote, that you instantiate the object only once before the for-loop and then you just keep rewriting its attributes. Moving the instantiation (= calling of new) inside the for-loop fixes the functionality.
However, apart from this, it is a very bad practice to increment the for-loop variable inside the for-loop body. Thus you obscure your intention and you will get a code which is less readable, harder maintainable and easier to break by later changes.
And the main condition should be i < newImageVal.length-1 to handle the array size safely. (To be 100% sure you do not get ArrayIndexOutOfBoundsException.)
There are multiple better ways.
Increment by 2 in the for-loop "header":
for (int i = 0; i < newImageVal.length-1; i += 2) {
ObjectAttribute object = new ObjectAttribute();
object.setImageName(newImageVal[i]);
object.setImageId(newImageVal[i+1]);
objLst.add(object);
}
Use while-loop instead of for-loop:
int i = 0;
while (i < newImageVal.length-1) {
ObjectAttribute object = new ObjectAttribute();
object.setImageName(newImageVal[i++]);
object.setImageId(newImageVal[i++]);
objLst.add(object);
}
or you may do something like this using the streams way:
AtomicInteger ai = new AtomicInteger();
List<ObjectAttribute> objLst = Arrays.stream(newImageVal)
.map(img-> {
ObjectAttribute object = new ObjectAttribute();
object.setImageName(img);
object.setImageId(ai.getAndIncrement());
return obj;
}).collect(Collectors.toList())

traversing a 2d array and adding indexs to a stack

I have a project for school to take my current pacman program and have pacman traverse the 2-d char array to find a pattern to complete the maze.
I am trying to use a stack and add specific index of my maze to the stack so when pacman reaches the index it pops off and he chooses a direction randomly to another index and so forth until all dots are eaten. My issue is taking my 2d array and finding the index values of the intersections and then adding them to a stack.
I am new to java and not really sure how to approach this I posted my maze I have and some code that will use the stack to find the sequence. Thanks in advanced.
private void create() {
String[] tier = new String[tall];
tier[0] = "|======================================|";
tier[1] = "|......................................|";
tier[2] = "|.====.==========================.====.|";
tier[3] = "|.||||............................||||.|";
tier[4] = "|.====.==========================.====.|";
tier[5] = "|......................................|";
tier[6] = "|.====================================.|";
tier[7] = "|......................................|";
tier[8] = "|.====.======.====----====.======.====.|";
tier[9] = "|.||||........|| ||........||||.|";
tier[10] = "|.||||.======.|| ||.======.||||.|";
tier[11] = "|.||||........|| ||....... ||||.|";
tier[12] = "|.====.======.============.======.====.|";
tier[13] = "|......................................|";
tier[14] = "|.===========..............===========.|";
tier[15] = "|.............===== =====.............|";
tier[16] = "|.=======.===.||$ $||.===.=======.|";
tier[17] = "|.|||||||.===.===== =====.===.|||||||.|";
tier[18] = "|.|||||||......................|||||||.|";
tier[19] = "|.|||||||.====================.|||||||.|";
tier[20] = "|.=======......................=======.|";
tier[21] = "|.==......====================......==.|";
tier[22] = "|.==.====.======........======.====.==.|";
tier[23] = "|....====........======........====....|";
tier[24] = "|======================================|";
for (int i = 0; i < tall; i++) {
array[i] = tier[i].toCharArray();
}
}
public boolean isPattern(Spot b, Spot e) {
Stack<Spot> ss = new Stack<Spot>();
Spot topPost, nextPost;
allOld();
ss.push(b);
markOld(b);
topPost = ss.peek();
while (!ss.empty() && (topPost.compareTo(e) != 0)) {
nextPost = getNextSpot(topPost);
if (nextPost == null) {
ss.pop();
} else {
ss.push(nextPost);
markOld(nextPost);
}
topPost = ss.peek();
}
if (ss.empty()) {
return false;
} else {
return true;
}
}
public void index(int x, int y, int dx, int dy){
x=array.length;
y=array[x].length;
for( int i=0;i <x;i++){
for(int j =0; j<y;j++){
if(array[i].get(i))//this should determine if its aninersection and then add to the stack
}
}
}
}
the last method is where i am getting stuck. I dont know how to get the specific index values. I guess i can enter them manually but I am sure there is an easier way. Please comment if need more context on the problem and Thanks again.

Linked List Optimization

I'm working on this program that emulates restriction enzymes and DNA splicing. I'm using DnaSequenceNode[s] as linked list nodes.
I have a problem with one of the function in my code, cutSplice() is supposed to create a new DnaStrand that is a clone of the current DnaStrand, but with every instance of enzyme replaced by splicee.
For example, if the LinkedDnaStrand is instantiated with "TTGATCC", and
cutSplice("GAT", "TTAAGG") is called, then the linked list should become something like (previous pointers not shown):
first -> "TT" -> "TTAAGG" -> "CC" -> null
My function works. However, my method cutSplice() takes more than 80 seconds to splice 200 DNAs. I'm supposed to bring that 80 seconds to 2 seconds.
This is all my code for the class : LinkedDnaStrand.java
And here's the code for the method cutSplice()
public DnaStrand cutSplice(String enzyme, String splicee) {
DnaStrand newStrand = null;
String original_Dna = this.toString();
String new_Dna = original_Dna.replaceAll(enzyme, splicee);
String[] splicee_split = new_Dna.split(splicee); // splits the new DNA string DnaStrand
newStrand = null;
int i = 0;
if (original_Dna.startsWith(enzyme)) {
newStrand = new LinkedDnaStrand(splicee);
} else {
newStrand = new LinkedDnaStrand(splicee_split[0]);
newStrand.append(splicee);
}
for (i = 1; i < splicee_split.length - 1; i++) {
String node = splicee_split[i];
newStrand.append(node);
newStrand.append(splicee);
}
newStrand.append(splicee_split[splicee_split.length - 1]);
if (original_Dna.endsWith(enzyme)) {
newStrand.append(splicee);
}
return newStrand;
}
Does anybody see anything that could make a critical difference on the time this function takes to process 200 DNAs sample?
Well, it is comfortable to use the string methods, but you are losing time in converting to the string, back to sequence, and (as pointed out in the previous comments) with the regex based string functions.
It will certainly consume less time to operate on the linked list directly, although this will require you to implement the replacement algorithm yourself:
#Override
public LinkedDnaStrand cutSplice(String enzyme, String splicee)
{
LinkedDnaStrand strand = new LinkedDnaStrand();
DnaSequenceNode end = null;
DnaSequenceNode begin = top;
int pos = 0;
DnaSequenceNode tmpStart, tmpEnd;
for (DnaSequenceNode current = top; current != null; current = current.next)
{
if(current.value != enzyme.charAt(pos))
{
tmpStart = tmpEnd = new DnaSequenceNode(begin.value);
for (DnaSequenceNode n = begin.next; n != current.next; n = n.next)
{
DnaSequenceNode c = new DnaSequenceNode(n.value);
tmpEnd.next = c;
c.previous = tmpEnd;
tmpEnd = c;
}
}
else if(++pos == enzyme.length())
{
tmpStart = tmpEnd = new DnaSequenceNode(splicee.charAt(0));
for (int i = 1; i < splicee.length(); ++i)
{
DnaSequenceNode c = new DnaSequenceNode(splicee.charAt(i));
tmpEnd.next = c;
c.previous = tmpEnd;
tmpEnd = c;
}
}
else
{
continue;
}
if(end == null)
{
strand.top = end = tmpStart;
}
else
{
end.next = tmpStart;
tmpStart.previous = end;
}
end = tmpEnd;
begin = current.next;
pos = 0;
}
return strand;
}
I do not claim that there is not any opportunity to further optimize, but this should be a lot faster as the original version. I tested it successfully with the example you gave, if you yet find a bug, feel free to fix it yourself...
Note 1: I did explicitely create a new sequence from the string (instead of using the constructor) to get the end of the sequence without having to iterate over it again.
Note 2: I assumed existing a constructor DnaSequenceNode(char value) and DnaSequenceNode having a member public char value. You might have to adjust the code appropriately if any of these assumptions fails.

How to get array data with CATIA using com4j API to get point coordinate?

I try to retreive information from catia usig com4j. Some methods require to pass an array in argument to retreive information but the array is never populated. In this example is to get coordinate from a point in catia.
The declaration of the method generated by com4j
public interface Point extends com4j.catia.HybridShape {
...
void getCoordinates(java.lang.Object[] oCoordinates);
...
}
my code to get the coordinate
public static void testGetPointCoordinates() {
String catiafile="E:\\test.CATPart";
Application app =null;
app = COM4J.createInstance(Application.class, "CATIA.Application");
Documents documents = app.documents();
Document oDocument = (Document) documents.open(new Holder<>(catiaFile.getAbsolutePath()));
PartDocument partDocument = oDocument.queryInterface(PartDocument.class);
Part part = partDocument.part();
Factory HSFactory = part.hybridShapeFactory();
HybridShapeFactory HSF = HSFactory.queryInterface(HybridShapeFactory.class);
HybridBodies hbodies = part.hybridBodies();
int n = hbodies.count();
for (int i = 1; i <= n; i++) {
HybridBody hbody = null;
hbody = hbodies.item(i);
int nbitems = hbody.hybridShapes().count();
for (int j = 1; j <= nbitems; j++) {
String name = hbody.hybridShapes().item(j).name();
System.out.println("name=" + name);
//Object tab[]=new Object[3];
if (name.startsWith("Point.12")) {//true point
HybridShape hs = hbody.hybridShapes().item(j);
Reference reference = part.createReferenceFromObject(hs);
HybridShapePointCoord p3 = hs.queryInterface(HybridShapePointCoord.class);
//works
System.out.println("point name = " + p3.name());
System.out.println(p3.y().value());//display 50.0
//doesn't work
Variant tab[] = new Variant[3];
for (int k = 0; k < 3; k++) {
Variant variant = new Variant();
variant.set(k);
tab[k] = variant;
}
p3.getCoordinates(tab);
System.out.println(tab[1].getParseableString()); //display 1 (value not modified)
//doesn't work
tab = new Variant[3];
for (int k = 0; k < 3; k++) {
Variant variant = new Variant(Variant.Type.VT_EMPTY);//tested with VT_R4 VT_R8,...
tab[k] = variant;
}
System.out.println(tab[1].getJavaCode()); //display null (Don't know how to print VT_EMPTY as an Java literal)
//doesn't work with this other solution but ok in VBA
tab = new Variant[3];
//Variant v = new Variant(Type.VT_EMPTY);
tab[0] = new Variant(Variant.Type.VT_EMPTY);
tab[1] = new Variant(Variant.Type.VT_EMPTY);
tab[2] = new Variant(Variant.Type.VT_EMPTY);
HybridShapePointExplicit point = HSF.addNewPointDatum(reference);
point.getCoordinates(tab);
System.out.println(tab[1].doubleValue() + " " + tab[2].toString()); //display 0
//doesn't work
//crash JVM
// tab = new Variant[3];
// p3.getCoordinates(tab);
break;
}
}
}
}
the code below works in VBA with CATIA
Dim P1
Dim coordonnees(2)
Dim coordonnees2(100, 3)
coordonnees(0) = 0
coordonnees(1) = 0
coordonnees(2) = 0
Set P1 = HSF.AddNewPointDatum(hbody.HybridShapes.Item(i))
'fonction to get coordinates
P1.GetCoordinates coordonnees
'set name and coordinates
coordonnees2(Y, 0) = hbody.HybridShapes.Item(i).name
coordonnees2(Y, 1) = Round(coordonnees(0), 3)
coordonnees2(Y, 2) = Round(coordonnees(1), 3)
coordonnees2(Y, 3) = Round(coordonnees(2), 3)
I'm not familiar with com4j, but Point.GetCoordinates is a restricted method:
.
The solution to this problem in VB is you need to create a new variant and set it equal to p3. Then, call GetCoordinates from the variant's context. Intellisense will not work well on the variant, but the call to GetCoordinates will work.
In VB the code would look something like this:
...
Dim p3 As Variant
Dim arrayOfCoord(2) As Variant
Set p3 = hybridShapePointCoord1 'set variant = strongly typed point object
p3.GetCoordinates arrayOfCoord
...
In your case, non-VB, your code might look like this
...
Object p3Obj; //used in vb:Variant p3Var;
p3Obj = p3;
p3Obj.GetCoordinates(tab);//Intellisense will not work, but the call to this method should
...
Let me know if this works.

Categories

Resources