This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
I trying to replace the value in the arraylist of edge under the updateEdge() method.
At If statement, the value of the edge.a.name and edge.b.name matches my source and dest value but somehow it doesn't enter the IF condition.
What I found out is this, edge.a = Node#55f96302 and a.name = Node#55f96302.
What I know this when I print out the node address, both does not match.
private ArrayList<Node> nodes = new ArrayList<Node>();
private ArrayList<Edge> edges = new ArrayList<Edge>();
//add new node
public void addNode(String nodeName)
{
Node node = new Node(nodeName);
nodes.add(node);
}
//add edge
public void addEdge(String source, String dest, String weight)
{
Node a, b;
a = new Node(source);
b = new Node(dest);
Double w = Double.parseDouble(weight);
Edge edge = new Edge(a, b, w);
edges.add(edge);
}
//Check index of the node
public int indexOfNode(String name)
{
for (int i = 0; i < nodes.size(); i++)
{
if(nodes.get(i).name.equals(name))
{
return i;
}
}
return -1;
}
//update edge
public void updateEdge(String source, String dest, String weight)
{
Node a, b;
a = nodes.get(indexOfNode(source));
b = nodes.get(indexOfNode(dest));
Double w = Double.parseDouble(weight);
for(int i = 0; i < edges.size(); i++)
{
Edge edge = edges.get(i);
if(edge.a.name == a.name && edge.b.name == b.name)
{
edge.weight = w;
}
}
}
a String is an object, when you compare two objects in java by using the == operator, you compare their hashcode and class, hence the 'Node' and 55f96302.
An int or double (for instance) are primitive types and hence can be compared with the == operator. They actually have to, seeing as how they don't have any methods for comparison since they are not objects (Integer and Double are their class counterparts).
In order to compare two strings based on their character array values, you will need to use the .equals() method:
edge.a.name.equals(a.name)
I assume name is a string
replace if(edge.a.name == a.name && edge.b.name == b.name)
with if(edge.a.name.equals(a.name) && edge.b.name.equals(b.name))
Related
This question already has answers here:
How to override toString() properly in Java?
(15 answers)
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 2 years ago.
I am trying to write an function incrList(L, x) that copies a given Linear Linked List, L, recursively and increment by a constant value, x. When I compile in terminal I got IntList#6ff3c5b5, which is a memory location, instead of the actual list. I only want to change the function incrList itself to give the right output.
public class IntList {
public int first;
public IntList rest;
public IntList(int f, IntList r) {
first = f;
rest = r;
}
}
public class Lists1Exercises{
public static IntList incrList(IntList L, int x) {
if (L == null){
return null;
}else {
IntList head = new IntList(L.first+x, null);
head.rest = incrList(L.rest, x);
return head;
}
}
public static void main(String[] args) {
IntList L = new IntList(5, null);
L.rest = new IntList(7, null);
L.rest.rest = new IntList(9, null);
System.out.println(incrList(L, 3));
}
}
You need to override the toString method in your intlist class or write a method to convert from intlists to strings. You are returning an object, and by default they print as locations in memory.
public class IntList {
public int first;
public IntList rest;
public IntList(int f, IntList r) {
first = f;
rest = r;
}
#override
public String toString() {
// or whatever you want to print
return "First: " + first + " | Rest: " + rest;
}
}
By default the .toString() 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.
But you can change it using #override and return whatever you want (usually something meaningful).
My assignment is to create a non-directed, unweighted graph class called Graph. My second part is to create a method 'count' which is passed a Graph object as an argument and returns a
count of the number of connected components in the graph.
For some reason whenever I run this 'count' method, I get returned 'I expect '1'. I think my error has to do with my 'getToVertices' method, which says all of these nodes are connected, even though I don't believe I made them connected purposefully. Attached is my getToVertices method and my 'count' method.
It's suppose to return 3, the connected nodes and 2 unconnected nodes. Am I missing something?
public QueueInterface<T> getToVertices(T vertex)
// Returns a queue of the vertices that vertex is adjacent to.
{
QueueInterface<T> adjVertices = new LinkedQueue<T>();
int fromIndex;
int toIndex;
fromIndex = indexIs(vertex);
for (toIndex = 0; toIndex < numVertices; toIndex++)
if (edges[fromIndex][toIndex] != true)
adjVertices.enqueue(vertices[toIndex]);
return adjVertices;
}
public class CountCC {
private static int count(Graph <String> graph)
{
int count = 0;
StackInterface<String> stack = new LinkedStack<String>();
QueueInterface<String> vertexQueue = new LinkedQueue<String>();
String currVertex; // vertex being processed
String adjVertex;
String startVertex;
graph.clearMarks();
while(graph.getUnmarked() != null)
{
startVertex = graph.getUnmarked();
graph.markVertex(startVertex);
stack.push(startVertex);
do
{
currVertex = stack.top();
stack.pop();
System.out.println(currVertex);
vertexQueue = graph.getToVertices(currVertex);
while (!vertexQueue.isEmpty())
{
adjVertex = vertexQueue.dequeue();
if (!graph.isMarked(adjVertex))
{
graph.markVertex(adjVertex);
stack.push(adjVertex);
}
}
} while (!stack.isEmpty());
count++;
System.out.println(graph.getUnmarked());
}
return count;
}
public static void main(String[] args) {
Graph<String> graph1=new Graph<String>();
String s0 = new String("0 ");
String s1 = new String("1 ");
String s2 = new String("2 ");
String s3 = new String("3 ");
String s4 = new String("4 ");
graph1.clearMarks();
graph1.addVertex(s0);
graph1.addVertex(s1);
graph1.addVertex(s2);
graph1.addVertex(s3);
graph1.addVertex(s4);
graph1.addEdge(s0, s1);
graph1.addEdge(s1, s2);
graph1.addEdge(s2, s0);
System.out.println("I expect "+ count(graph1));
}
}
Writing a method meant to store a list element to a variable in order to switch it with the next element in the array.
There are currently two variables for storage (which may or may not mean there's an extra).
The goal is to use the correct iterator (unless there's a better method) to switch the stored element with the next in the fewest lines possible.
public void sort(List<Point> lst) {
for (int st = 0; st < lst.size(); st++) { //defines first element-to-compare.
for (int wt = 1; wt< lst.size(); wt++) { //defines second element-to-compare.
double one = lst.get(st).distanceToOrigin(); //stores variable describing distance-to-origin for point one;
//if lst.get(st)>lst.get(wt), am switching element places in list.
//if lst.get(st) > lst.get(wt), switch the pair of consecutive elements.
double two = lst.get(wt).distanceToOrigin(); //stores variable describing distance-to-origin for point two;
//represents element to switch if lst.get(wt) < lst.get(st)
Point tmp1;
Point tmp2;
if (one > two){
tmp1 = lst.get(st);
lst.remove(lst.get(st));
tmp2 = lst.nextPoint();
}
}
}
}
Right now I'm using the hasNext() method in order to check if there is another element after lst.get(st):
if (one > two) {
tmp1 = lst.get(st);
lst.remove(lst.get(st));
while (lst.distanceToOrigin.hasNext()) { //this line does not work in editor.
//Attempting to refine.
//TODO switch elements described by double one and double two.
}
}
Insight is greatly appreciated.
You can use the methods of List for changing the elements order:
if(one > two) {
Point tmp1 = list.get(st);
Point tmp2 = list.get(wt);
lst.set(st, tmp2);
lst.set(wt, tmp1);
}
//....
Another approach: If each Point-Object "knows" the origin, it could also be an option to use the Comparable-Interface:
public class Point implements Comparable {
Point origin;
//other variables...
//constructor and methods...
#Override
public int compareTo(Point other) {
Double.compare(this.distanceToOrigin(), other.distanceToOrigin());
}
}
And your sort()-method:
public void sort(List<Point> lst) {
Collections.sort(lst);
}
we have sequence of 4 characters (A,B,C and D)that map to numbers form 1 to n.
we define components to be:
Component(k) :
A {cell[k]}
if Color(left_k) = Color(k)
then
A <-- A U Component(left_k)
if Color(right_k) = Color(k)
then
A <-- A U Component(left_k)
return A
there is 3 types of operations(the numbers in list indicate the input):
by giving index it should remove the component in that index(the numbers mapping to characters are fixed)
example : AABBBDA is the string. if index is 3 it should return AADA
by giving index it should rotate the string based on the component on that index(the numbers mapping to characters are fixed)
example : AABBBDA is the string. if index is 3 it should return DABBBAA
it should print the string.
inputs are like:
1 2 --> first operation with index=2
2 3 --> second operation with index=3
3 --> third operation
It's an assignment, happy to get help.
this is what i've tried so far:
public static void main(String[] args)
{
int numberOfOps;
String[] print = new String[30];
List list = new List();
Scanner input = new Scanner(System.in);
int count = input.nextInt();
String colors = new String();
colors = input.next();
for(int i = 0; i < count; i++)
{
list.add(colors.charAt(i));
}
numberOfOps = input.nextInt();
list.printElement();
for (int i = 0; i < numberOfOps; i++)
{
int op = input.nextInt();
if(op == 1)
{
int index = input.nextInt();
char c = list.item[index];
int temp = index;
int prevIndex = index;
int nexIndex = index;
if(index != 0)
{
while (list.item[--index] == c)
{
prevIndex--;
}
while (list.item[++temp] == c)
{
nexIndex++;
}
list.setNext(prevIndex-1, nexIndex+1);
}
else
{
while (list.item[++temp] == c)
{
nexIndex++;
}
list.setNext(prevIndex, nexIndex+1);
}
}
if(op == 2)
{
int index = input.nextInt();
}
if(op == 3)
{
print[i] = list.printElement();
}
}
}
here is my List class:
public class List {
// reference to linked list of items
public static final int MAX_LIST = 20;
public static final int NULL = -1;
public char item[] = new char[MAX_LIST]; // data
public int avail;
public int next[] = new int[MAX_LIST]; // pointer to next item
private int numItems; // number of items in list
public List()
{
int index;
for (index = 0; index < MAX_LIST-1; index++)
next[index] = index + 1;
next[MAX_LIST-1] = NULL;
numItems = 0;
avail = 0;
} // end default constructor
public void add(char e)
{
item[avail] = e;
avail = next[avail];
numItems++;
}
public String printElement()
{
String temp = null;
int index = 0;
while(index<avail)
{
temp += item[index];
System.out.println(item[index]);
index = next[index];
}
return temp;
}
public int size()
{
return numItems;
}
public void setNext(int i, int value)
{
next[i] = value;
}
}
if you test it you'll get, it has lots of problems, such as, I have no idea to do the rotate operation, and it has problem with connecting two components when the middle component has been removed.
This is a difficult question to answer, because the requirements are not properly stated.
For example the first bunch of pseudo-code does not make it clear whether A is a set, a multi-set or a list. The notation (use of curly brackets, and U (union?)) seems to say set ... but the output seems to be a list. Or maybe it is supposed to be a schema for a data structure??
And even the inputs are not clearly described.
But putting that on one side, there is still room for some (hopefully) helpful advice.
Make sure that >>you<< understand the requirements. (I imagine that the real requirements for the assignment are better stated than this, and the details have been "lost in translation".)
I would actually use an array list (or a StringBuilder) rather than a linked list for this. (But a properly implemented linked list ... implementing the List API ... would work.)
But whatever data structure you chose, there is no point in implementing it from scratch ... unless you are specifically required to do that. There are perfectly good list classes in the Java standard libraries. You should reuse them ... rather than attempting to reinvent the wheel (and doing a bad job).
If you are required to implement your own data structure type, then your current attempt is a mess. It looks like a hybrid between an array list and a linked list ... and doesn't succeed in being either. (For example, a decent array list implementation does not need a MAX_LIST, and doesn't have next pointers / indexes. And a linked list does not have any arrays inside it.)
This question already has answers here:
Why can't we use '==' to compare two float or double numbers [duplicate]
(3 answers)
Closed 6 years ago.
I have this class
public class Point {
private Double[] coordinates;
private int dimension;
public Point(Double[] coordinates) {
dimension = coordinates.length;
this.coordinates = new Double[dimension];
for(int i = 0; i < dimension; i++)
this.coordinates[i] = coordinates[i];
}
public Double getCoord(int n) {
if(n < 0 || n > dimension -1 ){
throw new RuntimeException("error de coordenadas");
}
return coordinates[n];
}
public int getDim() {
return dimension;
}
public boolean equals(Object p1){
if( (p1 instanceof Point) ){
Point p = (Point) p1;
int n = p.getDim();
if(getDim() == n)
{
for(; n > 0; n--)
{
if( Double.valueOf(this.getCoord(n-1)) != Double.valueOf(p.getCoord(n-1)) ) // <------- BAD LINE!
{
System.out.println("Checking coord " + (n-1));
System.out.println("Coord " + (n-1) + " p = " + Double.valueOf(this.getCoord(n-1)));
System.out.println("Coord " + (n-1) + " p2 = " + Double.valueOf(p.getCoord(n-1)));
return false;
}
}
}
return true;
}
return false;
}
}
And this main
public class FigureTest {
public static void main(String[] args){
Double[] coord1 = {2.0,3.3};
Double[] coord2 = {2.0,3.3};
Point p = new Point(coord1);
Point q = new Point(coord2);
System.out.println(p.equals(q));
}
}
I can't understand why this p.equals(q) returns false! It goes inside the if( Double.valueOf(... but then prints that both coordinates are equal. It's the same if I remove the Double.valueOf. The only way it worked was when I put ! if(this.getCoord(n-1).equal(p.getCoord(n-1)), but I don't understand why the others don't work.
Double.valueOf returns a Double object, not a primitive double.
You perform a reference check (!=). So even if Double.valueOf(getCoords(n-1)) returned the same numeric value for both calls, different objects would be wrapping the numbers, so the != check would be true, causing your equals to return false.
Here's a quick example:
public static void main(String[] args){
System.out.println(Double.valueOf(5) == Double.valueOf(5));
}
Notice how it returns false. That's because == is a reference check, and a different object is being returned each time you call Double.valueOf. So when you do
Double.valueOf(...) != Double.valueOf(...)
That check will return true, since the valueOf calls didn't return the same object. This is why the check in your code returns true, resulting in equals returning false.
To fix this, you could...
Change your != check into a .equals check, which will compare the numeric values rather than the references.
Double.valueOf(...).equals(Double.valueOf(...));
This returns true if both share the same numeric value.
Or you could use doubleValue() when you call getCoord:
getCoord(n-1).doubleValue() != other.getCoord(n-1).doubleValue()
This will avoid the excess creation of Double objects.
In order to this to work;:
p.equals(q)
you need to keep the contract between Hashcode and equals and override properly both of them: equals AND hashcode in the class Point, and when I write properly I mean specifically this:
Please refer to this question if you dont know why or that you dont need it
Double.valueOf(this.getCoord(n-1)) != Double.valueOf(p.getCoord(n-1))
if the members of the class Point are doubles, then you are right when you compare those doubles as criteria to decide if p1.equals(p2)
but according to the documentation of the class Double, the static method Double.compare(this.getCoord(n-1)),p.getCoord(n-1) must be use in order to compare 2 doubles content.
hence I recommend to do in the equals method some similar to this
if( Double.compare(this.getCoord(n-1)),p.getCoord(n-1)!=0) )