I'm trying to create ArrayList with elements from Database. I can get data from DB without any problem, but my problem occurs when I'm trying to create ArrayList of objects. It just doesn't exist. I've declared my list in my main class like this:
private static ArrayList<Vertex> vertexList = new ArrayList<Vertex>();
In my getData() function shown below
private static void getData() throws SQLException{
result = query.executeQuery("SELECT * FROM GTABLE ORDER BY X,Y");
while (result.next()){
int x = result.getInt("X");
int y = result.getInt("Y");
float p = result.getFloat("P");
System.out.printf("X:%d\tY:%d\tP:%.3f\n",x,y,p);
addData(x,y,p);
addData(y,x,p);
}
}
I'm getting all the data from database. Everything works fine until I get to my function addData(x,y,p) shown below:
private static void addData(int x, int y, float p){
Edge edge;
int tmp;
Vertex vertex = new Vertex(x);
edge = new Edge(x,y,p);
//vertex.edgeList.add(edge);
tmp = ifVertexExists(vertex);
if(tmp < 0){
vertexList.add(vertex);
} else {
//vertexList.get(tmp).edgeList.add(edge);
}
}
It just doesn't create anything in my list. I've checked it with isEmpty() and it it was empty.
Any help will be appreciated.
EDIT Here's my Vertex class:
class Vertex{
private final int vertID;
public Vertex(int x){
this.vertID = x;
}
public int getVertID(){
return vertID;
}}
ifVertexExists
private static int ifVertexExists(Vertex vL){
for(Vertex v : vertexList){
if(v.getVertID() == vL.getVertID()){
System.out.printf("Vertex is on the list\n");
return -1;
} else {
System.out.println("No vertex with this ID\n");
}
}
return 0;
}
Right now, I can create the list and it works well, the vertex are shown on screen, tmp is -1. It was bad ifVertexExists, thanks to everyone who helped.
Presumably the response from ifVertexExists is always > 0. Use a debugger or insert print statements to verify this.
I think your vertex class needs to implement equals to be used with ArrayList.contains which you might be using in ifVertexExists.
Related
import java.util.*;
class Graph{
class Edge{
int v,w;
public Edge(int v,int w){
this.v=v; this.w=w;
}
#Override
public String toString(){
return "("+v+","+w+")";
}
}
List<Edge> G[];
public Graph(int n){
G=new LinkedList[n];
for(int i=0;i<G.length;i++)
G[i]=new LinkedList<Edge>();
}
boolean isConnected(int u,int v){
for(Edge i: G[u])
if(i.v==v) return true;
return false;
}
void addEdge(int u,int v,int w)
{
G[u].add(0,new Edge(v,w));
G[v].add(0,new Edge(u,w));
}
public int getWeight(int u, int v)
{
int w;
return w;
}
This part right above ^^^^. I'm trying to make it so that the code returns the correct number associated with the two numbers already input. For example g.getWeight(6,3) should return 13 since that is the weight in the graph for those two numbers.
#Override
public String toString(){
String result="";
for(int i=0;i<G.length;i++)
result+=i+"=>"+G[i]+"\n";
return result;
}
}
public class GraphEx
{
public static void main(String[] args)
{
Graph g=new Graph(10);
g.addEdge(1,2,38);
g.addEdge(1,5 ,19);
g.addEdge(1,3 ,35);
g.addEdge(1,4 ,11);
g.addEdge(4,3,27);
g.addEdge(3,6,13);
g.addEdge(3,5,28);
g.addEdge(5,6,26);
System.out.println(g);
g.getWeight(6,3);
}
}
The error the code as it currently stands gives is "variable w might not have been initialized"
variable w might not have been initialized
This is because of Definite assignment.
Each local variable (§14.4) and every blank final field (§4.12.4, §8.3.1.2) must have a definitely assigned value when any access of its value occurs.
Unlike member variables, you have to assign local variables before you use their value. You can simply assign a value; but this won't do what you need yet:
int w = 0; // Or -1, or Integer.MAX_VALUE, or something.
To implement this method, you have to search through the edges of G[u], looking for an edge whose target is v, and return its weight.
For example:
for (Edge e : G[u]) {
if (e.v == v) { return e.w }
}
throw new NoSuchElementException(); // Or return a default value.
Note that mixing arrays and generics is not a good idea:
List<Edge> G[];
Better to use a full-generics solution:
Map<Integer, List<Edge>> G = new HashMap<>();
in your code
public int getWeight(int u, int v)
{
int w; // There's no need, delete this
return w;
}
You were creating a new variable and didn't initialize it.
And you have to search in G[], the right edge.
I've got an ArrayList filled with 500 Point-Objects. There might be duplicates in it so I want to find them and if needed delete them except for one. The plan is: Check for each Point in the arrayList, if there is an equal Point, if so, add it to a List, after the test for each Point, delete all Points from the original List that are also in the toRemove-List.
But here comes the Problem: If i run this, its going for an endless loop. Do I have a serious thinking error? I think it might be a really simple misstake but I cant think about it
Also, if you have any proposal on how to do this better, let me know.
This is my method:
private void checkForDuplicates() {
ArrayList <Point> toRemove=new ArrayList<Point>();
int i=0;
while(i<points.size()) {
Point local=points.get(i);
for (Point p: points) {
if (local!=p && local.equals(p)) {
toRemove.add(p);
}
}
for (Point p: toRemove) {
points.remove(p);
}
i++;
}
}
Update:
Something is really broken. It looks like the method might work right now, but my programm isnt. The code isnt running anymore if I call this method somewhere. I cant even print out something on the console as the first line in my main method while i call checkForDuplicates() somewhere else?!
Point:
public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
#Override
public boolean equals(Object p) {
if (this == p) {
return true;
}
if (!(p instanceof Point)) {
return false;
}
Point point = (Point) p;
return this.getX() == point.getX() && this.getY() == point.getY();
}
}
I recommend using streams for this task:
List result =
points
.stream()
.distinct()
.collect(Collectors.toCollection(ArrayList::new));
To make distinct() work as expected, you will probably have to define an equals()method for your Point class.
User Frank Puffer has answered the question in Java 8. It seems as if you're in older version of Java, so the following might help you. It just creates a Set object and copies the ArrayList to it. Because the Set will remove the duplicates automatically you don't need to make the code much more complexer than it should be, and is less error prone.
private void removeDuplicates() {
Set<Point> distinctPoints = new HashSet<>();
for (Point p : points) {
distinctPoints.add(p);
}
points = new ArrayList<String>(distinctPoints);
}
And include the following method impl to the Point class so that Point objects can be searched in the Set:
#Override
public int hashCode() {
int hashValue = 11;
hashValue = 31 * hashValue + x;
hashValue = 31 * hashValue + y;
return hashValue;
}
#Override
public String toString() {
return "Point[" + X + ", " + Y + "]";
}
The toString() method is a nice to have feature.
So I'm setting a node class that shows links between one node and another to find the shortest route. I decided to use a seperate object class to store the links between node A and B to avoid using two-dimensional arrays.
After saving the project in eclipse, just as a checkpoint so I don't lose my data, all of a sudden red lines appeared under any calls of DistanceBetween, saying that the method doesn't exist in that object class, although it does, as you'll see.
Note: Any bolded part is throwing an error, in Node. Generally it states that the method doesn't exist in DistanceBetween, or that the constructor (int, int) is wrong, when it is not.
Should I use extend, a package?
public class DistanceBetween{
private int thisAddress;
private int distanceBetween;
public DistanceBetween(int myAddress, int myDistance){
thisAddress = myAddress;
myDistance = distanceBetween;
}
public int getAddress(){
return thisAddress;
}
public void setAddress(int newAddress){
thisAddress = newAddress;
}
public int getDistance(){
return distanceBetween;
}
public void setDistance(int newDistance){
distanceBetween = newDistance;
}
}
public class Node{
private int address;
private int distance;
private Node[] connectedNodes;
private DistanceBetween[] distances;
private boolean intersection;
public Node(int myAddress, Node[] myConnected, DistanceBetween[]
myDistances, boolean isIntersection){
address = myAddress;
connectedNodes = myConnected;
distances = myDistances;
intersection = isIntersection;
}
public int getThisAddress(){
return address;
}
public void setThisAddress(int newAddress){
address = newAddress;
}
public Node[] getConnected(){
return connectedNodes;
}
public void connectTwo(Node a, Node b){
for(int x = 0; x < a.getConnected().length; x++){
if(a.getConnected()[x].getThisAddress() == 0){
}
}
}
public DistanceBetween[] getDistances(){
return distances;
}
public void setDistances(DistanceBetween[] newDistances){
distances = newDistances;
}
public void addLink(Node a, Node b, int thisDistance){
DistanceBetween[] holderDistanceA = a.getDistances();
DistanceBetween[] holderDistanceB = a.getDistances();
int flags = 0;
for(int x = 0; x < holderDistanceA.length; x++){
if(holderDistanceA[x].**getAddress()** == 0){
DistanceBetween aAndB = new **DistanceBetween(b.getThisAddress(),thisDistance);**
holderDistanceA[x] = aAndB;
flags++;
break;
}
}
for(int x = 0; x < holderDistanceB.length; x++){
if(holderDistanceB[x].**getAddress()** == 0){
DistanceBetween bAndA = new **DistanceBetween(a.getThisAddress(),thisDistance);**
holderDistanceB[x] = bAndA;
break;
}
}
if(flags < 1){
System.out.println("Error, cannot add a link, link load is full.");
}
a.setDistances(holderDistanceA);
b.setDistances(holderDistanceB);
}
public int getDistanceBetween(Node a, Node b){
int result = 0;
for(int x = 0; x < a.getDistances().length; x++){
if(a.getDistances()[x].**getAddress()** == b.getThisAddress()){
result = a.getDistances()[x].**getDistance()**;
}
}
return result;
}
public boolean equals(Node a, Node b){
if(a.address == b.address){
return true;
}else
return false;
}
}
Your code compiles fine, it would appear that you have the 2 classes in different packages. To fix you can:
put the 2 classes into the same package
import the DistanceBetween package into the Node class.
import yourpackagename.DistanceBetween;
Make sure you do not have a class named DistanceBetween somewhere else in your project, or, in case you do, that you're importing the right one where the DistanceBetween code you posted is intended to be used.
The Open Type tool in Eclipse (Ctrl + Shift + T) allows you to search for the location of classes along your workspace.
I'm trying to create a 2D array of an image in Java.
Here's what I have so far:
public int[][] GetArray() { //NetBeans is saying 'Illegal Start of Expression' on this line
getimage data;
getwidth;
getheight;
int[][] array = new int[width][height];
for (loop through width) {
for (loop through height) {
array[q][p] = raster.getSample(p, q, 0);
}
}
return array;
I tried setting the return part to:-
return array[][];
but that produced an error saying cannot find symbol.
I'm relatively new to Java and I really want to get better quickly, if you could help me out, I'd really appreciate it.
If you'd like to return an array, do it like this
return array; // CORRECT
What you are doing is incorrect.
return array[][]; // INCORRECT
Your function should look like this
public class MyClass
{
// main is a method just like GetArray, defined inside class
public static void main(String[] args)
{
// do something
}
// other methods are defined outside main but inside the class.
public int[][] GetArray() {
int width = 5; // change these to your dimensions
int height = 5;
int[][] array = new int[width][height];
int q,p;
for(q=0;q<width;q++)
{
for(p=0;p<height;p++)
{
array[q][p] = raster.getSample(p, q, 0);
}
}
return array;
}
}
when you return an array you should not use
return array[][];
you should not use the square brackets [][] . In the return statement we should not mention the dimensions of the array
instead use
return array; this is the correct way
I want to crate a Heap structure that each node have 2 data , 1) string 2) int
so i think that each node must be a Class that's name is "heapNode" , but i have a trouble in swap method ,
please help me
import java.util.ArrayList;
public class MainHeap {
ArrayList<heapNode> heap;
MainHeap (){
new ArrayList<heapNode>();
}
public int getMin(){
return heap.get(0).data ;
}
private int parent(int pos) {
return pos / 2;
}
private void swap(int pos1, int pos2) {
heapNode temp =new heapNode();
temp = heap.get(pos1);
heap.get(pos1) = heap.get(pos2);
heap.get(pos2) = temp;
}
public void insert(int elem) {
int max = heap.size();
heap.get(max).data = elem ;
int current = heap.size() ;
while (heap.get(current).data < heap.get(parent(current)).data){
swap ( current , parent(current));
}
}
}
and this is my heapNode class
public class heapNode {
int data;
String fileName;
}
the swap method has error but i cant solve errors
Your swap code actually makes the objects point to different objects. It does not modify the positions in the arraylist itself. If using arraylist, you will have to remove an object from an index and set that object at a new index to swap or else you can use other data structure.
java.util.PriorityQueue<YourClass>