dustinboettcher
dustinboettcher

Reputation: 515

Java - List<Node> two values

I'm stuck again.

I have a List<Node> node with some values (6, 14) (6, 13) (6, 12)

shown with

for (Node n : node)
 System.out.print(n);

I don't want to change the List type but want to use the Numbers e.g. (6,14) and save them separately to an int.

int x = 6;
int y = 14;

I tried several things but nothing seems work work work except node.get(0) which just shows the whole node at 0.

Any Ideas?

Upvotes: 0

Views: 2655

Answers (3)

user1889970
user1889970

Reputation: 736

Look at code below

import java.util.ArrayList;
import java.util.List;


class Node {
private int x; 
private  int y;
public int getX() {
    return x;
}
public void setX(int x) {
    this.x = x;
}
public int getY() {
    return y;
}
public void setY(int y) {
    this.y = y;
}
public Node(int x, int y) {
    super();
    this.x = x;
    this.y = y;
}



}

public class stackov1 {

/**
 * @param args
 */
public static void main(String[] args) {



List<Node> node= new ArrayList();
node.add(new Node(10,12));
node.add(new Node(11,14));

for (Node n : node){
    System.out.println(n.getX());
    System.out.println(n.getY());
// System.out.print(n);
}
}

}

Upvotes: 0

Howard Schutzman
Howard Schutzman

Reputation: 2135

Your question is not clear, but I will attempt to answer it by making the following assumptions:

1) By Node, you mean the interface org.w3c.dom.Node

2) Each element in node (your List variable) is also a Node.

3) The elements which are Nodes contain two child nodes. Each child node consists of an integer value.

If the above assumptions are correct, here is some code to retrieve the integer values from the first list element.

Node element0 = node.get(0);
NodeList children = element0.getChildNodes();
Node intNode0 = children.item(0);
Node intNode1 = children.item(1);
int x;
int y;
try {
  x = Integer.parseInt(intNode0.getTextContent());
  y = Integer.parseInt(intNode1.getTextContent());
} catch (Exception e) {
  System.out.println("Child node is not integer value");
}

`

Upvotes: 1

Dev2007
Dev2007

Reputation: 29

If you use c++,I will tell you that you can use operator overloading. The System.out.print(n); in c++, looks like std::cout<<n; ,you can print anything you want,such as 6 or 14,even 6+14. But in Java,node.get(0) maybe the only way,because Java hasn't operator overloading,any operator base on function. You can use function do the same thing by operator overloading.You can get 6 by n.get(0), also can create a function do 6+14.

Upvotes: 0

Related Questions