Problem Adding incremented class member variable to arraylist inside loop - java

Trying to add an incremented class member variable 'nNodeIndex' to arraylist, but at the end of the loop all the values stored are identical to the last iteration increment??
Class with member variable:
import java.util.ArrayList;
public class Graph {
private static ArrayList<GraphNode> Nodes = new ArrayList<GraphNode>();
private static ArrayList<GraphEdge> Edges = new ArrayList<GraphEdge>();
private static boolean diGraph;
private static int nNodeIndex;
private boolean uniqueEdge(int from, int to)
{
for(int i=0; i< Edges.size(); i++){
if(Edges.get(i).from() == from && Edges.get(i).to() == to)
return false;
}
return true;
}
private void removeInvalidEdges(int nodeIndex)
{
for(int i=0; i<Edges.size(); i++)
{
if(Edges.get(i).from() == nodeIndex)
Edges.remove(i);
if(Edges.get(i).to() == nodeIndex)
Edges.remove(i);
}
}
Graph(boolean directionalGraph)
{
diGraph = directionalGraph;
nNodeIndex = 1;
}
public GraphNode getNode(int nodeIndex)
{
return Nodes.get(nodeIndex);
}
public int getIndexByVector(int x, int y)
{
for(int i=0; i<Nodes.size(); i++)
{
if(Nodes.get(i).x() == x && Nodes.get(i).y() == y)
return i;
}
return -1;
}
public int nextFreeNodeIndex(){ return nNodeIndex; }
public void addNode(GraphNode node)
{
if(Nodes.size() > 0)
Nodes.add(node.index()-1, node);
else
Nodes.add(node);
nNodeIndex++;
}
public void removeNode(int index)
{
Nodes.get(index).setIndex(-1);
removeInvalidEdges(index);
}
public void addEdge(GraphEdge edge)
{
if(uniqueEdge(edge.from(), edge.to()))
Edges.add(edge);
if(!diGraph)
{
if(uniqueEdge(edge.to(), edge.from()))
Edges.add(new GraphEdge(edge.to(), edge.from()));
}
}
public void removeEdge(GraphEdge edge)
{
for(int i=0; i<Edges.size(); i++)
if(Edges.get(i).from() == edge.from() &&
Edges.get(i).to() == edge.to())
{
Edges.remove(i);
}
}
public int totalNodes(){ return Nodes.size(); }
public int totalEdges(){ return Edges.size(); }
public int nActiveNodes()
{
int count = 0;
for(int i=0; i<Nodes.size(); i++)
{
if(Nodes.get(i).index() != -1 )
count++;
}
return count;
}
public void reset()
{
nNodeIndex = 1;
Nodes.clear();
Edges.clear();
}
}
Use within main class:
for(int row = 1; row <= boardWidth; row++){
for(int col = 1; col <= boardHeight; col++){
graph.addNode(new GraphNode(graph.nextFreeNodeIndex(), row, col));
}
}
Graph Node class:
public class GraphNode extends Square {
private static int indexNum;
GraphNode(int n, int x, int y)
{
super(x,y);
indexNum = n;
}
public int index(){ return indexNum; }
public void setIndex(int index){ indexNum = index; }
}

Do you need to show us the GraphNode class? I wonder if the node index held by it (set by the first parameter passed in its constructor) is a static variable.

Related

How can I avoid java.lang.ArrayIndexOutOfBoundsException when joining a Queue?

I'm working on a simple(?) exercise for my Data Structures class. It works fine right up until I have an element leave the queue then try to add another one on at which point I get the following error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10
at queueExercise.IntegerQueue.join(IntegerQueue.java:20)
at queueExercise.IntegerQueueTest.main(IntegerQueueTest.java:27)
My code is as follows:
Queue Constructor Class:
public class IntegerQueue {
private int[] queue;
private int front;
private int end;
private int noInQueue;
private int count;
private boolean full;
public IntegerQueue(int max) {
queue = new int[max];
front = end = 0;
full = false;
}
public void join(int newValue) {
if (isFull()==false) {
queue[end] = newValue;
count++;
if (end == queue.length) {
end = 0;
}
else {
end++;
}
}else
System.out.println("Error: Queue Full");
}
public int leave() {
if (isEmpty()==false) {
noInQueue = queue[front];
queue[front]=0;
front++;
if (front==queue.length) {
front = 0;
}
count--;
}
else {
System.out.println("Error: Queue Empty");
}
System.out.println("Leaving: "+noInQueue);
return noInQueue;
}
public boolean isEmpty() {
if (count == 0){
return true;
}
else
return false;
}
public boolean isFull() {
if (count >= queue.length) {
return true;
}
else
return false;
}
public void printQueue() {
if (!isEmpty()) {
System.out.println("Printing Queue");
int pos = front;
int i =0;
while(i<queue.length) {
System.out.println(queue[pos]);
pos++;
i++;
if (pos >=queue.length) {
pos = 0;
}
}
}
}
}
Test Class
public class IntegerQueueTest {
static IntegerQueue q = new IntegerQueue(10);
public static void main(String[] args) {
int j;
System.out.println("Creating Queue");
for (int i = 0; i <10; i++) {
j = (int)(Math.random()*100);
if (!q.isFull()) {
q.join(j);
System.out.println("Adding: "+j);
}
}
q.printQueue();
q.join(112);
q.leave();
q.leave();
q.leave();
q.printQueue();
q.join(112);
q.join(254);
q.printQueue();
}
}
The problem is in the join method and more precisely in the condition if (end == queue.length). All you have to do is change it to if (end == queue.length - 1).

Can I add elements to a java queue using array without defining the front and the rear? I am having trouble with this

I am having trouble using enqueue and dequeue functions. I want to add elements without defining the front and rear in my scope.
public class MyStaticQueue
{
private int items[] ;
private int noOfItems = 0;
private int maxItems;
public MyStaticQueue(int m)
{
this.maxItems = m;
this.items = new int[maxItems];
this.noOfItems = 0;
}
public boolean isEmpty()
{
if(noOfItems == 0)
{
return true;
}
else
{
return false;
}
}
public int first()
{
return items[0];
}
public void add(int item)
{
for (int i=0; i<items[maxItems]; i++)
{
if (items[i] == 0)
{
items[i] = item;
}
noOfItems++;
}
}
}

How do I test delete() in the class growingArray

I'm learning the Growing Array in Java, and I implemented the method delete() in the following Code.
Now I want to test this method for a example array [1,2,3,4,5,6,7]
What do I have to write in the Main method?
import java.util.Arrays;
public abstract class GrowingArray {
protected Object[] array;
protected static final int primaryQty = 10;
protected static final int secondaryQty = 5;
protected int index = 0;
public GrowingArray() {
array = new Object[primaryQty];
}
public GrowingArray(int size) {
array = new Object[size];
}
protected void grow() {
int oldsize = array.length;
int newsize = oldsize + secondaryQty;
Object[] loc = new Object[newsize];
for (int i = 0; i < oldsize; i++)
loc[i] = array[i];
array = loc;
}
public Object get(int at) {
return array[at];
}
public int getLength() {
return array.length;
}
public void add(Object obj) {
if (index < array.length)
array[index++] = obj;
else {
grow();
array[index++] = obj;
}
}
public void delete(int x) {
for (int i = x; i < array.length; i++) {
if (i == array.length - 1) {
array[i] = null;
System.out.println(array.toString());
} else {
array[i] = array[i + 1];
System.out.println(array.toString());
}
}
}
#Override
public boolean equals(Object obj) {
if (obj instanceof GrowingArray) {
return Arrays.equals(array, ((GrowingArray) obj).array);
}
return false;
}
#Override
public String toString() {
return Arrays.toString(array);
}
public static void main(String args[]) {
//test ?????
}
}
Your class is abstract. Remove abstract from the class definition.

Java Hashtable Chaining

I am supposed to write a Java Hashtable function being able to import java.util.Iterator, java.util.NoSuchElementException, and java.util.ConcurrentModificationException. There is no specific on what type of Hashing function to use. SO how do I write my getHashCode function. My code so far:
package data_structures;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import data_structures.LinkedListDS.IteratorHelper;
public class Hashtable<K,V> implements DictionaryADT<K,V> {
private int currentSize,maxSize,tableSize;
private long modCounter;
private LinkedListDS <DictionaryNode<K,V>> [] list;
class DictionaryNode<K,V> implements Comparable<DictionaryNode<K,V>> {
K key;
V value;
public DictionaryNode(K k, V v) {
key = k;
value = v;
}
public int compareTo(DictionaryNode<K,V> node) {
return ((Comparable<K>)key).compareTo((K)node.key);
}
}
public Hashtable(int n) {
currentSize = 0;
maxSize = n;
modCounter = 0;
tableSize = (int) (maxSize * 1.3f);
list = new LinkedListDS[tableSize];
for (int i=0; i < tableSize; i++)
list[i] = new LinkedListDS<DictionaryNode<K,V>>();
}
public boolean contains(K key) {
return list[getHashCode(key)].contains(new DictionaryNode<K,V>(key,null));
}
private int getHashCode(K key) {
// TODO Auto-generated method stub
return 0;
}
public boolean insert(K key, V value) {
if (isFull())
return false;
if (list[getHashCode(key)].contains(new DictionaryNode<K,V>(key,null)))
return false;
list[getHashCode(key)].addLast(new DictionaryNode<K,V>(key,value));
currentSize++;
modCounter++;
return true;
}
#Override
public boolean remove(K key) {
if (isEmpty())
return false;
if (!list[getHashCode(key)].contains(new DictionaryNode<K,V>(key,null)))
return false;
list[getHashCode(key)].remove(new DictionaryNode<K,V>(key,null));
currentSize--;
modCounter++;
return true;
}
public V getValue(K key) {
DictionaryNode<K,V> tmp = list[getHashCode(key)].find(new DictionaryNode<K,V>(key,null));
if (tmp == null)
return null;
return tmp.value;
}
#Override
public K getKey(V value) {
DictionaryNode<K,V> tmp = list[getHashCode(value)].find(new DictionaryNode<K,V>(null,value));
if (tmp == null)
return null;
return tmp.key;
}
public int size() {
return currentSize;
}
#Override
public boolean isFull() {
return currentSize == maxSize;
}
public boolean isEmpty() {
return currentSize == 0;
}
#Override
public void clear() {
currentSize = 0;
modCounter++;
for (int i=0; i<tableSize; i++)
list[i].makeEmpty();
}
public Iterator<K> keys() {
return new KeyIteratorHelper();
}
public Iterator<V> values() {
return new ValueIteratorHelper();
}
abstract class IteratorHelper<E> implements Iterator<E> {
protected DictionaryNode<K,V> [] nodes;
protected int idx;
protected long modCheck;
public IteratorHelper() {
nodes = new DictionaryNode[currentSize];
idx = 0;
int j = 0;
for (int i=0; i < tableSize; i++)
for (DictionaryNode n : list[i])
nodes[j++] = n;
nodes = (DictionaryNode<K,V>[]) ObjectSorter.quickSort(nodes);
}
public boolean hasNext() {
if (modCheck != modCounter)
throw new ConcurrentModificationException();
return idx < currentSize;
}
public abstract E next();
public void remove() {
throw new UnsupportedOperationException();
}
}
class KeyIteratorHelper<K> extends IteratorHelper<K> {
public KeyIteratorHelper() {
super();
}
public K next() {
return (K) nodes[idx++].key;
}
}
class ValueIteratorHelper<V> extends IteratorHelper<V> {
public ValueIteratorHelper() {
super();
}
public V next() {
return (V) nodes[idx++].value;
}
}
}

graphic.addAnimation calling addAnimation

I run this code:
graphic.addAnimation("standart",new int[] {0,1},1.0,true);
which calls the graphic.addAnimation(String,int[],float,boolean) Method:
public void addAnimation(String nme,int[] frmes,float time,boolean loop) {
animations.push(new Aim(nme, frmes, time, loop));
}
but I get this error:
the function addAnimation(String,int[],float,boolean) does not exist.
SpriteSheet:
package progame;
import java.util.Stack;
import processing.core.PImage;
public class SpriteSheet extends Graphic {
public int height,width,index;
public int timer;
public String playing;
public Stack<PImage> sheet = new Stack<PImage>();
public Stack<Aim> animations = new Stack<Aim>();
public SpriteSheet(String path,int h,int w) {
super(path);
height = h;
width = w;
for(int i = 0; i < Math.floor(source.height/height); i++) {
for(int j = 0; j < Math.floor(source.width/width); j++) {
sheet.push(source.get(j*width, i*height, width, height));
}
}
}
public SpriteSheet(String path,Entity e,int h,int w) {
super(path,e);
height = h;
width = w;
for(int i = 0; i < Math.floor(source.height/height); i++) {
for(int j = 0; j < Math.floor(source.width/width); j++) {
sheet.push(source.get(j*width, i*height, width, height));
}
}
}
public Aim getAnimation(String name) {
for(int i = 0; i< animations.size(); i++)
{
if(animations.get(i).name == name) {
return(animations.get(i));
}
}
return null;
}
public void play(String name) {
for(int i = 0; i< animations.size(); i++)
{
if(animations.get(i).name == name) {
playing = name;
index = 0;
timer = 0;
}else
{
playing = null;
return;
}
}
}
public void update() {
timer ++;
Aim aim = getAnimation(playing);
if( timer > aim.frameRate)
{
timer = 0;
if(index == aim.frames.length)
{
if(aim.looping) {
index = 0;
}else
{
playing = null;
}
}else
{
index++;
}
}
source = sheet.get(index);
}
public void render() {
update();
super.render();
}
public void addAnimation(String nme,int[] frmes,float time,boolean loop) {
animations.push(new Aim(nme, frmes, time, loop));
}
private class Aim
{
String name;
int[] frames;
float frameRate;
boolean looping;
public Aim(String nme,int[] frmes,float time,boolean loop)
{
name = nme;
frames = frmes;
frameRate = time;
looping = loop;
}
}
}
Where did you obtain the instance 'graphic' from in the following line?
graphic.addAnimation("standart",new int[] {0,1},1.0,true);
Or more importantly, what is its declaration? You can't call addAnimation on a variable of type Graphic. As it's SpriteSheet that defined this method.
Based on OP's comment: its declared in the Entity class, like this: public Graphic graphic;
((SpriteSheet)graphic).addAnimation("standart",new int[] {0,1},1.0,true);
would fix the problem.
You said
its declared in the Entity class, like this: public Graphic graphic;
Declare it as:
public SpriteSheet graphic;

Categories