using Adjacency list structure for directed graph java - java

I have problem to implement the transpose of a graph using only Adjacency List, without Edge List. Every vertex of the graph has a positional list that stores adjacent vertexes. When you have to transpose the graph, every element stored in a list of a vertex A, has to be removed and used as a source vertex. So if we have the situation
A -> B
B after its removal, add to its own adjacent list the old source Vertex A
We have as result:
B -> A
when I update the lists, i override the last information stored in, so I lose connection between vertexes.
public class Vertice implements Comparable<Vertice>{
public Vertice(int valore){
this.valore = valore;
this.color = Color.WHITE;
this.distanza = 0;
this.padre = null;
adiacenze = new NodePositionList<Vertice>();
}
public int getValore() {
return valore;
}
public void setValore(int valore) {
this.valore = valore;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public Position<Vertice> getPadre() {
return padre;
}
public void setPadre(Position<Vertice> padre) {
this.padre = padre;
}
public int getDistanza() {
return distanza;
}
public void setDistanza(int distanza) {
this.distanza = distanza;
}
public enum Color{
BLACK, WHITE, GREY;
}
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append("v_" + valore );
return sb.toString();
}
public boolean equals(Vertice v){
return this.compareTo(v) == 0;
}
#Override
public int compareTo(Vertice o) {
return this.valore - o.getValore();
}
public int getFin() {
return fin;
}
public void setFin(int fin) {
this.fin = fin;
}
public Position<Vertice> getRiferimentoVertice() {
return riferimentoVertice;
}
public void setRiferimentoVertice(Position<Vertice> riferimentoVertice) {
this.riferimentoVertice = riferimentoVertice;
}
public Iterable<Vertice> getAdiacenze() {
return adiacenze;
}
public void setAdiacenze(NodePositionList<Vertice> adiacenze) {
this.adiacenze = adiacenze;
}
public Position<Vertice> addNodoAdiacente(Vertice v){
Position<Vertice> newVertice = adiacenze.addLast(v);
v.setRiferimentoAsAdiacenza(newVertice);
return newVertice;
}
public Position<Vertice> removeNodoAdiacente(Position<Vertice> v){
return adiacenze.remove(v);
}
public Position<Vertice> getRiferimentoAsAdiacenza() {
return riferimentoAsAdiacenza;
}
public void setRiferimentoAsAdiacenza(Position<Vertice> riferimentoAsAdiacenza) {
this.riferimentoAsAdiacenza = riferimentoAsAdiacenza;
}
public boolean hasAdiacent(){
return adiacenze.size() == 0;
}
public boolean hasRedEdge(){
return redEdge;
}
public void setHasRedEdge(boolean redEdge){
this.redEdge = redEdge;
}
private boolean redEdge;
private int valore;
private Color color;
private Position<Vertice> padre;
private int distanza;
private int fin;
private Position<Vertice> riferimentoVertice;
private Position<Vertice> riferimentoAsAdiacenza;
private NodePositionList<Vertice> adiacenze;
here the "Grafo.java" class
public class Grafo {
public Grafo(int numV){
verticiGrafo = new NodePositionList<Vertice>();
listaArchi = new NodePositionList<Arco>();
this.V = numV;
}
public Position<Vertice> addVertice(Vertice v){
Position<Vertice> newAdded = verticiGrafo.addLast(v);
v.setRiferimentoVertice(newAdded);
return newAdded;
}
public NodePositionList<Vertice> getVertici(){
return verticiGrafo;
}
public Position<Arco> addArco(Arco a){
a.getSorgente().element().addNodoAdiacente(a.getDestinazione().element());
Position<Arco> newAdded = listaArchi.addLast(a);
a.setRiferimentoArco(newAdded);
return newAdded;
}
public Position<Arco> connect(Position<Vertice> sorgente, Position<Vertice> destinazione){
Arco a = new Arco(sorgente, destinazione);
Vertice v_sorgente = sorgente.element();
Vertice v_destinazione = destinazione.element();
v_sorgente.addNodoAdiacente(v_destinazione);
Position<Arco> newAdded = listaArchi.addLast(a);
a.setRiferimentoArco(newAdded);
return newAdded;
}
public Position<Arco> removeArco(Position<Arco> a){
a.element().getSorgente().element().removeNodoAdiacente(a.element().getDestinazione());
return listaArchi.remove(a);
}
public Iterable<Arco> archi(){
return listaArchi;
}
public void invertiArco(Position<Arco> a){
Arco a1 = a.element();
Position<Vertice> temp = a1.getDestinazione();
a1.setDestinazione(a1.getSorgente());
a1.setSorgente(temp);
Vertice sorgente = a1.getSorgente().element();
Vertice destinatario = a1.getDestinazione().element();
sorgente.addNodoAdiacente(destinatario);
}
public Position<Arco> getArcoByVertici(Position<Vertice> sorgente, Position<Vertice> destinazione){
for(Arco a: listaArchi){
if(a.getColor() == EdgeColor.NONE){
Vertice dest = a.getDestinazione().element();
Vertice sorg = a.getSorgente().element();
if(sorg.equals(sorgente.element()) && dest.equals(destinazione.element())){
return a.getRiferimentoArco();
}
}
}
return null;
}
public void removeAllAdiacenze(){
for(Vertice v: this.getVertici()){
v.setAdiacenze( new NodePositionList<Vertice>());
}
}
public void setColorArco(Position<Arco> a, EdgeColor ec){
a.element().setColor(ec);
}
public NodePositionList<Arco> getListaArchi() {
return listaArchi;
}
public void setListaArchi(NodePositionList<Arco> listaArchi) {
this.listaArchi = listaArchi;
}
private NodePositionList<Vertice> verticiGrafo;
private NodePositionList<Arco> listaArchi; //lista archi uscenti
public final int V;
}
here the method on the "Ricerca.java" class that I'm trying to make
public static Grafo traspostaGrafo(Grafo g){
NodePositionList<Vertice> npl = g.getVertici();
Position<Vertice> u = npl.first();
while (u != npl.getTail()){
u.element().setColor(Color.WHITE);
NodePositionList<Vertice> adiacenti = g.getListaAdiacenti(u.element().getValore());
Position<Vertice> adiacente = adiacenti.first();
while (adiacente != adiacenti.getTail() && adiacente.element().getFlag() == 0){
g.addNodoAdiacente(adiacente.element(), u.element());
g.removeNodoAdiacente(adiacente);
adiacente = adiacenti.next(adiacente);
u.element().setFlag(1);
}
}
return g
}

Related

Can't set propertys of objects in an ObservableList

In my main class I initialise a static object (lkw), which contains the public ObservableList (ladung). Now I want to manipulate the data in the list whith the methode ergebniss, which is located in the class Methoden. I call the methode ergebniss in my JavaFx Gui. It doesn't work. I don't get an error, but the X property is empty. Also removing an element (Main.lkw.ladung.remove(j)) doesn't work.
What I do wrong?
EDIT
Code
Class Main
public class Main extends Application{
public static Lkw lkw=new Lkw();
public static void main(String[] args) {
javafx.application.Application.launch(Gui.class);
}
#Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
}
Class Lkw
public class Lkw {
private String name="";
private int länge=0;
private int breite=0;
private int höhe=0;
public ObservableList<Ladung> ladung=FXCollections.observableArrayList();
public Lkw(String name, int länge, int breite, int höhe){
this.name=name;
this.länge=länge;
this.breite=breite;
this.höhe=höhe;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public int getLänge() {
return länge;
}
public void setLänge(int länge) {
this.länge = länge;
}
public int getBreite() {
return breite;
}
public void setBreite(int breite) {
this.breite = breite;
}
public int getHöhe() {
return höhe;
}
public void setHöhe(int höhe) {
this.höhe = höhe;
}
public ObservableList<Ladung> getLadung() {
return ladung;
}
public void setLadung(ObservableList<Ladung> ladung) {
this.ladung = ladung;
}
Class Ladung
public class Ladung {
private int nr;
private int länge = 0;
private int breite = 0;
private int höhe = 0;
private int x = 0;
private int y = 0;
private int z = 0;
private int raum = 0;
private Rectangle farbe = new Rectangle(100, 50);
public Ladung(int nr, int länge, int breite, int höhe) {
this.nr = nr;
this.länge = länge;
this.breite = breite;
this.höhe = höhe;
this.farbe.setFill(new Color(Math.random(), Math.random(), Math.random(), 1));
}
public Ladung(int nr, int länge, int breite, int höhe, int raum, int x, int y, int z, Rectangle farbe) {
this.nr = nr;
this.länge = länge;
this.breite = breite;
this.höhe = höhe;
this.raum = raum;
this.x = x;
this.y = y;
this.z = z;
this.farbe=farbe;
}
public int getLänge() {
return länge;
}
public void setLänge(int länge) {
this.länge = länge;
}
public int getBreite() {
return breite;
}
public void setBreite(int breite) {
this.breite = breite;
}
public int getHöhe() {
return höhe;
}
public void setHöhe(int höhe) {
this.höhe = höhe;
}
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 int getZ() {
return z;
}
public void setZ(int z) {
this.z = z;
}
public int getNr() {
return nr;
}
public void setNr(int nr) {
this.nr = nr;
}
public int getRaum() {
return raum;
}
public void setRaum(int raum) {
this.raum = raum;
}
public Rectangle getFarbe() {
return farbe;
}
public void setFarbe(Rectangle farbe) {
this.farbe = farbe;
}
This is the class with some static methods
public class Methoden {
public static int einlesen(String pfad) {
int ret=0;
String zeile = "";
String[] daten = null;
FileReader fr = null;
try {
fr = new FileReader(pfad);
BufferedReader br = new BufferedReader(fr);
zeile = br.readLine();
daten = zeile.split(" ");
Main.lkw.setLänge(Integer.valueOf(daten[1]));
Main.lkw.setBreite(Integer.valueOf(daten[2]));
Main.lkw.setHöhe(Integer.valueOf(daten[3]));
zeile = br.readLine();
int j=0;
while (zeile != null) {
daten = null;
daten = zeile.split(" ");
Main.lkw.ladung.get(j).setX(Integer.valueOf(daten[5]));
Main.lkw.ladung.get(j).setY(Integer.valueOf(daten[6]));
Main.lkw.ladung.get(j).setZ(Integer.valueOf(daten[7]));
Main.lkw.ladung.get(j).setRaum(Integer.valueOf(daten[4]));
zeile = br.readLine();
}
br.close();
fr.close();
if(Main.lkw.getLadung().size()==0){
ret=-1;
}
for(int i=0;i<Main.lkw.getLadung().size();i++){
System.out.println(Main.lkw.getLadung().get(i));
System.out.println(Main.lkw.getLadung().get(i).getRaum());
if(Main.lkw.getLadung().get(i).getRaum()!=1){
ret=-1;
System.out.println("achtung!!!!");
}
}
} catch (IOException e) {
System.err.println(e.getMessage() + " " + e.getClass());
}
return ret;
}
I call the methode ergebniss from a JavaFx Gui class.

ImageViewer image loop from json codenameone

I have edited the question as your suggestions but null pointer exception is caught.I used connectionRequest instead of multipartRequest since i dont need to upload(just need to read the value frm json). All my codes below, please have a look.
Edited: exception
java.lang.NullPointerException
at userclasses.StateMachine$16.readResponse(StateMachine.java:1834)
at com.codename1.io.ConnectionRequest.performOperation(ConnectionRequest.java:438)
at com.codename1.io.NetworkManager$NetworkThread.run(NetworkManager.java:263)
at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)
Code:
#Override
protected void beforeImgGallery(Form f) {
int iter = 0;
GridLayout gr = new GridLayout(1, 1);
Container grid = new Container(gr);
gr.setAutoFit(true);
grid.setScrollableY(true);
grid.addComponent(new InfiniteProgress());
f.addComponent(BorderLayout.CENTER, grid);
f.removeAllCommands();
f.setBackCommand(null);
createPictureCommand(grid);
}
private static boolean animating;
private Vector<Map<String, Object>> responsesgallery;
String galleryPhotoUrl;
private void createPictureCommand(final Container grid) {
ConnectionRequest mp = new ConnectionRequest(){
#Override
protected void readResponse(InputStream input) throws IOException {
JSONParser p = new JSONParser();
results = p.parse(new InputStreamReader(input));
responsesgallery = (Vector<Map<String, Object>>) results.get("data");
//i've kept this for loop in postResponse but same error
for (int i = 0; i < responsesgallery.size(); i++) {
//null pointer exception in this line
final Button btn = createImageButton(i, grid, imageList.getSize());
//if i simply create a btn like below, it works
// final Button btn = new Button((URLImage.createToStorage(placeholder, token, galleryPhotoUrl, URLImage.RESIZE_SCALE_TO_FILL)));
imageList.addImageId(i);
grid.addComponent(i, btn);
Hashtable hm = (Hashtable) responsesgallery.get(i);
String galleryImgId = (String) hm.get("news_id");
galleryPhotoUrl = (String) hm.get("photo");
}
}
};
mp.setUrl("http://capitaleyedevelopment.com/~admin/traffic/api/news/getLatestNews");
NetworkManager.getInstance().addToQueueAndWait(mp);
}
ImageList imageList;
Button createImageButton(final int imageId, final Container grid, final int offset) {
final Button btn = new Button(URLImage.createToStorage(placeholder, token, galleryPhotoUrl, URLImage.RESIZE_SCALE_TO_FILL));
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
imageList.setSelectedIndex(offset);
final Container viewerParent = new Container(new LayeredLayout());
ImageViewer viewer = new ImageViewer(imageList.getItemAt(offset));
viewerParent.addComponent(viewer);
Container parent = new Container(new BorderLayout());
viewerParent.addComponent(parent);
viewer.setImageList(imageList);
grid.getParent().replace(grid, viewerParent, CommonTransitions.createSlide(CommonTransitions.SLIDE_HORIZONTAL, false, 300));
Display.getInstance().getCurrent().setBackCommand(createBackCommand(viewerParent, grid));
}
});
return btn;
}
public static final String SERVER_URL = "http://capitaleyedevelopment.com/~admin/traffic/api/news/getLatestNews";
class ImageList implements ListModel<Image> {
private int selection;
private long[] imageIds;
private EncodedImage[] images;
private EventDispatcher listeners = new EventDispatcher();
public void addImageId(int id) {
long[] n = new long[imageIds.length + 1];
EncodedImage[] nImages = new EncodedImage[n.length];
System.arraycopy(imageIds, 0, n, 0, imageIds.length);
System.arraycopy(images, 0, nImages, 0, images.length);
n[imageIds.length] = id;
imageIds = n;
images = nImages;
listeners.fireDataChangeEvent(-1, DataChangedListener.ADDED);
}
public long getSelectedImageId() {
return imageIds[selection];
}
public ImageList(long[] images) {
this.imageIds = images;
this.images = new EncodedImage[images.length];
}
public Image getItemAt(final int index) {
if (images[index] == null) {
images[index] = placeholder;
Util.downloadUrlToStorageInBackground(IMAGE_URL_PREFIX + imageIds[index], "FullImage_" + imageIds[index], new ActionListener() {
public void actionPerformed(ActionEvent evt) {
try {
images[index] = EncodedImage.create(Storage.getInstance().createInputStream("FullImage_" + imageIds[index]));
listeners.fireDataChangeEvent(index, DataChangedListener.CHANGED);
} catch (IOException err) {
err.printStackTrace();
}
}
});
}
return images[index];
}
public int getSize() {
return imageIds.length;
}
public int getSelectedIndex() {
return selection;
}
public void setSelectedIndex(int index) {
WebServiceProxy.getPhotoLikesAsync(imageIds[selection], new Callback<Integer>() {
public void onSucess(Integer value) {
}
public void onError(Object sender, Throwable err, int errorCode, String errorMessage) {
}
});
selection = index;
}
public void addDataChangedListener(DataChangedListener l) {
listeners.addListener(l);
}
public void removeDataChangedListener(DataChangedListener l) {
listeners.removeListener(l);
}
public void addSelectionListener(SelectionListener l) {
}
public void removeSelectionListener(SelectionListener l) {
}
public void addItem(Image item) {
}
public void removeItem(int index) {
}
}
In the Photo Share demo (that's on github) I demonstrate something pretty similar. I used a custom list model that fetches the images to the ImageViewer dynamically.
The interesting bit is this list model where the images are downloaded dynamically as needed:
class ImageList implements ListModel<Image> {
private int selection;
private long[] imageIds;
private EncodedImage[] images;
private EventDispatcher listeners = new EventDispatcher();
public void addImageId(long id) {
long[] n = new long[imageIds.length + 1];
EncodedImage[] nImages = new EncodedImage[n.length];
System.arraycopy(imageIds, 0, n, 0, imageIds.length);
System.arraycopy(images, 0, nImages, 0, images.length);
n[imageIds.length] = id;
imageIds = n;
images = nImages;
listeners.fireDataChangeEvent(-1, DataChangedListener.ADDED);
}
public long getSelectedImageId() {
return imageIds[selection];
}
public ImageList(long[] images) {
this.imageIds = images;
this.images = new EncodedImage[images.length];
}
public Image getItemAt(final int index) {
if(images[index] == null) {
images[index] = placeholder;
Util.downloadUrlToStorageInBackground(IMAGE_URL_PREFIX + imageIds[index], "FullImage_" + imageIds[index], new ActionListener() {
public void actionPerformed(ActionEvent evt) {
try {
images[index] = EncodedImage.create(Storage.getInstance().createInputStream("FullImage_" + imageIds[index]));
listeners.fireDataChangeEvent(index, DataChangedListener.CHANGED);
} catch(IOException err) {
err.printStackTrace();
}
}
});
}
return images[index];
}
public int getSize() {
return imageIds.length;
}
public int getSelectedIndex() {
return selection;
}
public void setSelectedIndex(int index) {
WebServiceProxy.getPhotoLikesAsync(imageIds[selection], new Callback<Integer>() {
public void onSucess(Integer value) {
if(likeCount != null) {
likeCount.setText("" + value);
likeCount.getParent().revalidate();
}
}
public void onError(Object sender, Throwable err, int errorCode, String errorMessage) {
}
});
selection = index;
}
public void addDataChangedListener(DataChangedListener l) {
listeners.addListener(l);
}
public void removeDataChangedListener(DataChangedListener l) {
listeners.removeListener(l);
}
public void addSelectionListener(SelectionListener l) {
}
public void removeSelectionListener(SelectionListener l) {
}
public void addItem(Image item) {
}
public void removeItem(int index) {
}
}

A-star, H value nullpointer (Java)

I'm working on an A* pathfinding algorithm, and for some reason at a certain point I get a null pointer exception and I have no idea why. The problem occurs at class Astar line 79, which is a simple seter for the H value.
Here is the Astar class:
import java.util.*;
public class Astar {
private int[][] map;
private int Infinity = Integer.MAX_VALUE;
private GridElement startElement;
private GridElement endElement;
private GridElement[][] grid;
private int currentX;
private int currentY;
private int tmpV;
private int adjacentX;
private int adjacentY;
//private int x;
//private int y;
private GridElement adjacentE;
private GridElement adjacentW;
private GridElement adjacentN;
private GridElement adjacentS;
public Astar(int[][] map, int xStart, int yStart, int xEnd, int yEnd) {
this.map= map;
grid = new GridElement[map.length][map[0].length];
for(int i=0;i<grid.length;i++)
for(int j=0;j<grid[0].length;j++){
grid[i][j]=new GridElement(i,j,map[i][j],grid);
grid[i][j].setG(map[i][j]);}
this.startElement=grid[xStart][yStart];
this.endElement=grid[xEnd][yEnd];
}
public void AstarAlgortihm() {
ArrayList<GridElement> openList = new ArrayList<GridElement>();
for(int i=0;i<grid.length;i++)
for(int j=0;j<grid[0].length;j++)
openList.add(grid[i][j]);
GridElement current = startElement;
GridElement next;
while(openList.isEmpty() == false){
openList.remove(current);
current.setVisited(true);
if(current==endElement)
break;
int northF=Infinity;
int southF=Infinity;
int westF=Infinity;
int eastF=Infinity;
if(current.hasNeighbour(1,0)!=null && grid[current.getX()+1][current.getY()].checkVisited() == false) {
adjacentS = current.hasNeighbour(1,0);
grid[current.getX()+1][current.getY()].setParent(current);
adjacentS.setH(H(current.getX()+1, current.getY()));
adjacentS.setF();
southF=adjacentS.getF();}
if(current.hasNeighbour(-1,0)!=null && grid[current.getX()-1][current.getY()].checkVisited()==false) {
adjacentN = current.hasNeighbour(-1,0);
grid[current.getX()-1][current.getY()].setParent(current);
adjacentN.setH(H(current.getX()-1, current.getY()));
adjacentN.setF();
northF=adjacentN.getF();}
if(current.hasNeighbour(0,1)!=null && grid[current.getX()][current.getY()+1].checkVisited()==false) {
adjacentE = current.hasNeighbour(1,0);
grid[current.getX()][current.getY()+1].setParent(current);
adjacentE.setH(H(current.getX(), current.getY()+1));
adjacentE.setF();
eastF=adjacentE.getF();}
if(current.hasNeighbour(0,-1)!=null && grid[current.getX()][current.getY()-1].checkVisited()==false) {
adjacentW = current.hasNeighbour(1,0);
grid[current.getX()][current.getY()-1].setParent(current);
adjacentW.setH(H(current.getX(), current.getY()-1));
adjacentW.setF();
westF=adjacentW.getF();}
if(northF <southF &&northF < westF &&northF< eastF){
current=adjacentN;
}
else if(eastF<southF && eastF< northF && eastF < westF){
current=adjacentE;
}
else if(westF < southF && westF < northF && westF<eastF){
current = adjacentW;
}
else
current=adjacentS;
}
if(current==endElement) {
while(current != startElement){
current.setIsPathmember(true);
current= current.getParent();
}
current.setIsPathmember(true);
} else System.out.println("No path found");
}
public int[][] getMap(){
int[][] tempmap = new int[grid.length][grid[0].length];
for(int i=0;i<grid.length;i++)
for(int j=0;j<grid[0].length;j++)
if(grid[i][j].getIsPathMember())
tempmap[i][j]=9;
else
tempmap[i][j]=grid[i][j].getCost();
return tempmap;
}
public int H(int x, int y){
int xCoords=(endElement.getX())- x ;
int yCoords=(endElement.getY()) - y ;
return xCoords+yCoords;
}
}
And here is the GridElement class. This is also the GridElement calss for a Dijkstra's algorithm ,s o if you see anything that shouldn't be there for Astar, that's the reason.
public class GridElement {
private int x;
private int y;
private int value;
private boolean isVisited;
private GridElement parent;
private int cost;
private boolean isWall;
private GridElement[][] map;
private boolean isPathMember;
private int g;
private int h;
private int f;
public GridElement(int x, int y, int cost, GridElement[][] map) {
this.x=x;
this.y=y;
this.isPathMember=false;
this.isVisited=false;
this.parent=null;
this.value=Integer.MAX_VALUE;
if(cost==0)
this.isWall=true;
else
this.isWall=false;
this.cost = cost;
this.map = map;
}
public int getX() {
return x;
}
public int getY(){
return y;
}
public void setValue(int v){
this.value=v;
}
public boolean checkVisited(){
return isVisited;
}
public int getValue(){
return value;
}
public void setParent(GridElement p){
this.parent=p;
}
public GridElement getParent(){
return parent;
}
public boolean checkWall(){
return isWall;
}
public void setVisited(boolean v){
this.isVisited=v;
}
public void setIsPathmember(boolean is) {
this.isPathMember = is;
}
public boolean getIsPathMember(){
return isPathMember;
}
public int getCost(){
return cost;
}
public void setG(int g){
this.g=g;
}
public void setH(int h){
this.h=h;
}
public void setF(){
this.f=g+h;
}
public int getF(){
return f;
}
public int getH(){
return h;
}
public int getG(){
return g;
}
public String toString() {
String tempString="";
tempString+="Node: "+getX()+","+getY()+","+getValue()+"|||";
return tempString;
}
public GridElement hasNeighbour(int horizontalShift, int verticalShift){ // Params will be -+1
if(getX()+horizontalShift>=0 && getX()+horizontalShift<map.length && getY()+verticalShift>=0 && getY()+verticalShift<map[0].length)
if(!map[getX()+horizontalShift][getY()+verticalShift].checkWall())
if(!map[getX()+horizontalShift][getY()+verticalShift].checkVisited())
return map[getX()+horizontalShift][getY()+verticalShift];
return null;
}
}
I see why there "could" be a null pointer, but shouldn't the if statement take care of that at the start ?
Thanks in advance!
if(current.hasNeighbour(0,1)!=null ...
adjacentE = current.hasNeighbour(1,0);
You're checking the wrong value in the if. current.hasNeighbor(0,1) != null, but current.hasNeighbor(1,0) == null. Someone copied and pasted and forgot to correct a parameter. ;)

Java LinkedList with Object

Trying to implement a LinkedList that simulates a Portfolio, consisting of Stock objects. I'm struggling to figure out how to properly iterate through the list and check if each stock contains certain parameters. the SHAREPRICE method is the one I'm having trouble with specifically, if someone could help with that, I'd be very grateful. What I have so far:
import java.util.*;
public class Portfolio<AnyType> implements Iterable<AnyType> {
public int balance, shares;
private Stock<AnyType> beginMarker, endMarker, temp;
LinkedList<Stock> Portfolio = new LinkedList<Stock>();
java.util.Iterator<Stock> iter = Portfolio.iterator();
public int CASHIN(int x) {
balance = x;
return balance;
}
public int CASHOUT(int y) {
balance = balance + (-y);
return balance;
}
public int CASHBALANCE() {
return balance;
}
public void BUY(String t, int s, float pp) {
temp = new Stock<AnyType>(t, s, pp, pp, 0, null, null);
Portfolio.add(temp);
shares = shares + s;
}
public void SELL(String t, int s, float pp) {
shares = shares - s;
}
public void SHAREPRICE(String t, float pp)
{
if(Portfolio.contains(Stock.)
{
}
}
public void QUERY(String t) {
}
public int COUNTPORTFOLIO() {
return shares;
}
public void PRINTPORTFOLIO() {
}
public java.util.Iterator<AnyType> iterator() {
return new Iterator();
}
private class Iterator implements java.util.Iterator<AnyType> {
private Stock<AnyType> current = beginMarker.next;
private boolean okToRemove = false;
public boolean hasNext() {
return current != endMarker;
}
public AnyType next() {
if (!hasNext())
throw new java.util.NoSuchElementException();
AnyType nextItem = (AnyType) current.getTicker();
current = current.next;
okToRemove = true;
return nextItem;
}
public void remove() {
if (!okToRemove)
throw new IllegalStateException();
Portfolio.this.remove(current.prev);
okToRemove = false;
}
}
private class Stock<AnyType> implements Comparable<Stock<AnyType>> {
public String getTicker() {
return ticker;
}
public void setTicker(String ticker) {
this.ticker = ticker;
}
public float getPurchasePrice() {
return purchasePrice;
}
public void setPurchasePrice(float purchasePrice) {
this.purchasePrice = purchasePrice;
}
public float getLatestPrice() {
return latestPrice;
}
public void setLatestPrice(float latestPrice) {
this.latestPrice = latestPrice;
}
public float getPctChange() {
return pctChange;
}
String ticker;
int sharesOwned;
float purchasePrice, latestPrice;
float pctChange = (latestPrice - purchasePrice) / purchasePrice;
Stock<AnyType> prev, next;
public Stock(String ticker, int sharesOwned, float purchasePrice,
float latestPrice, float pctChange, Stock<AnyType> prev,
Stock<AnyType> next) {
this.ticker = ticker;
this.sharesOwned = sharesOwned;
this.purchasePrice = purchasePrice;
this.latestPrice = latestPrice;
this.pctChange = pctChange;
this.prev = prev;
this.next = next;
}
public int compareTo(Stock<AnyType> pctChange) {
return ((Comparable) this.pctChange)
.compareTo(Stock.getPctChange());
}
}
}
class TestPortfolio {
public static void main(String[] args) {
}
}
Forward Direction:
while(itr.hasNext())
{
System.out.println(itr.next());
}
Reverse Direction
while(itr.hasPrevious())
System.out.println(itr.previous());
}

How To Create A Java Graph File from .txt file

I am trying to create a graph file .I have to read in values from a .gra file(which I think is a .txt file).We were told to tokenise lines based on a space in the format <vertex> <name> <x-coord> <y-coord>,same for edge
I had a look at a couple of related questions,but still cant find the answer.
Here's the code I was given:
public EdgeListVertex(V element) {
this.element = element;
}
#Override
public V element() {
return element;
}
public String toString() {
return element.toString();
}
}
private class EdgeListEdge implements Edge<E> {
Position<EdgeListEdge> position;
E element;
EdgeListVertex start, end;
public EdgeListEdge(EdgeListVertex start, EdgeListVertex end, E element) {
this.start = start;
this.end = end;
this.element = element;
}
#Override
public E element() {
return element;
}
public String toString() {
return element.toString();
}
}
private List<EdgeListVertex> vertices;
private List<EdgeListEdge> edges;
public EdgeListGraph() {
vertices = new LinkedList<EdgeListVertex>();
edges = new LinkedList<EdgeListEdge>();
}
#SuppressWarnings("unchecked")
#Override
public Vertex<V>[] endVertices(Edge<E> e) {
EdgeListEdge edge = (EdgeListEdge) e;
Vertex<V>[] endpoints = (Vertex<V>[]) new Vertex[2];
endpoints[0] = edge.start;
endpoints[1] = edge.end;
return endpoints;
}
#Override
public Vertex<V> opposite(Vertex<V> v, Edge<E> e) {
Vertex<V>[] endpoints = endVertices(e);
if (endpoints[0].equals(v)) {
return endpoints[1];
} else if (endpoints[1].equals(v)) {
return endpoints[0];
}
throw new InvalidVertexException();
}
#Override
public boolean areAdjacent(Vertex<V> v, Vertex<V> w) {
for (EdgeListEdge edge: edges) {
if ((edge.start.equals(v)) && (edge.end.equals(w))) return true;
if ((edge.end.equals(v)) && (edge.start.equals(w))) return true;
}
return false;
}
#Override
public V replace(Vertex<V> v, V x) {
EdgeListVertex vertex = (EdgeListVertex) v;
V temp = vertex.element;
vertex.element = x;
return temp;
}
#Override
public E replace(Edge<E> e, E x) {
EdgeListEdge edge = (EdgeListEdge) e;
E temp = edge.element;
edge.element = x;
return temp;
}
#Override
public Vertex<V> insertVertex(V v) {
EdgeListVertex vertex = new EdgeListVertex(v);
Position<EdgeListVertex> position = vertices.insertLast(vertex);
vertex.position = position;
return vertex;
}
#Override
public Edge<E> insertEdge(Vertex<V> v, Vertex<V> w, E o) {
EdgeListEdge edge = new EdgeListEdge((EdgeListVertex) v, (EdgeListVertex) w, o);
Position<EdgeListEdge> position = edges.insertLast(edge);
edge.position = position;
return edge;
}
#Override
public V removeVertex(Vertex<V> v) {
Iterator<Edge<E>> it = incidentEdges(v).iterator();
while (it.hasNext()) it.remove();
EdgeListVertex vertex = (EdgeListVertex) v;
vertices.remove(vertex.position);
return vertex.element;
}
#Override
public E removeEdge(Edge<E> e) {
EdgeListEdge edge = (EdgeListEdge) e;
edges.remove(edge.position);
return edge.element;
}
#Override
public List<Edge<E>> incidentEdges(Vertex<V> v) {
LinkedList<Edge<E>> list = new LinkedList<Edge<E>>();
for (EdgeListEdge edge : edges) {
if (edge.start.equals(v)) list.insertLast(edge);
if (edge.end.equals(v)) list.insertLast(edge);
}
return list;
}
#Override
public List<Vertex<V>> vertices() {
LinkedList<Vertex<V>> list = new LinkedList<Vertex<V>>();
for (EdgeListVertex vertex : vertices) {
list.insertLast(vertex);
}
return list;
}
#Override
public List<Edge<E>> edges() {
LinkedList<Edge<E>> list = new LinkedList<Edge<E>>();
for (EdgeListEdge edge : edges) {
list.insertLast(edge);
}
return list;
}
}
Any tips?
A good approach might be to create a new class with fields for vertex, name and coordinates. Then read in the data from a scanner into an ArrayList of the class you just created. After this, you could just pass the ArrayList into whatever you are using for graphing (which might require a few tweaks).
Example scanner code (untested):
File graphFile = new File(filepath);
Scanner graphScanner = new Scanner(graphFile);
Then, to read from the scanner (untested):
ArrayList<graphClass> dataPoints = new ArrayList<graphClass>(); //you will have to make graphClass
while(graphScanner.hasNextLine()) {
dataPoints.add(new graphClass(graphScanner.nextDouble(), graphScanner.next(), graphScanner.nextDouble(), graphScanner.nextDouble()); //assuming constructor of graphClass takes vertex, name, x, y in that order
I hope this helps.

Categories