A-star, H value nullpointer (Java) - 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. ;)

Related

RPG game code error [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I keep getting this error in my code. Can someone fix it and how is the code written? Can it be improved by maybe using setters and getters only?
Exception in thread "main" java.lang.NullPointerException
at Player.attack(Player.java:72)
at Main.main(Main.java:15)
My code:
Player.java
public class Player {
String name;
String race;
int hp;
int power;
int armour;
Weapon weapon;
public Player (String n, String r, int h, int p, int a) {
name = n;
race =r;
hp = h;
power = p;
armour = a;
}
public void setName (String n) {
name = n;
}
public String getName() {
return name;
}
public void setRace (String r) {
race = r;
}
public String getRace() {
return race;
}
public void setHP (int h) {
hp = h;
}
public int getHP() {
return hp;
}
public void setPower (int p) {
power = p;
}
public int getPower() {
return power;
}
public void setArmour (int a) {
armour = a;
}
public int getArmour() {
return armour;
}
public boolean dead() {
return hp <= 0;
}
public boolean equip(Weapon weapon) {
this.weapon = weapon;
return true;
}
public boolean receiveDamage(int i) {
if ((hp - i) > 0) {
hp = hp - i;
return true;
}
hp = 0;
return false;
}
public boolean attack(Player player) {
return player.receiveDamage(weapon.useWeapon());
}
}
Main.java
public class Main {
public static void main(String args[]) {
Player Mensch = new Player("Mensch", "Mensch", 85, 12, 10);
Player Ork = new Player("Shrek", "Ork", 50, 14, 6);
Weapon MenschW = new Weapon("mächtiges Schwert", 15, 100);
Weapon OrkW = new Weapon("große Axt", 7, 100);
Mensch.equip(Mensch.weapon);
Ork.equip(Ork.weapon);
while (!Mensch.dead() && !Ork.dead() ) { //Alternativ: for (player hp >=0)
System.out.println("Mensch gegen Ork " + Mensch.attack(Ork));
if (Mensch.dead() || Ork.dead()) {
break;
}
System.out.println("Mensch gegen Ork " + Ork.attack(Mensch));
}
System.out.println("Ork ist tot: " + Ork.dead());
System.out.println("Mensch ist tot: " + Mensch.dead());
}
}
Weapon.java
import java.util.concurrent.ThreadLocalRandom;
public class Weapon {
String name;
int damage;
int hp;
public Weapon(String string, int d, int hp) {
// TODO Auto-generated constructor stub
}
public void setName (String n) {
name = n;
}
public String getName() {
return name;
}
public void setDamage (int d) {
damage = d;
}
public int getDamage() {
return damage;
}
public void setWHP (int h) {
hp = h;
}
public int getWHP() {
return hp;
}
public int useWeapon() {
if
(broken())
return 0;
hp = hp - 5;
return (damage / 2) + random();
}
private int random() {
return ThreadLocalRandom.current().nextInt(1, damage + 1);
}
private boolean broken() {
return hp <= 0;
}
}
I know its a lot of code but I keep getting the same error, also I'm quite new to java so I would appreciate some tips or suggestions to make my code better or more failsave. The code doesn't do much yet but it will (hopefully) be a simple game soon in which two characters fight eachother with some calculations on damageoutput of each player. In this case a Human and Ork. Feel free to try it out
Change
Mensch.equip(Mensch.weapon); // Mensch.weapon is not initialized in constructor so it is null.
Ork.equip(Ork.weapon); // Ork.weapon is not initialized in constructor so it is null as well.
To
// Use your newly created weapons in the main instead.
Mensch.equip(MenschW );
Ork.equip(OrkW);

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.

Object in a 2d array keeps on resetting and I don't know why

I'm trying to make a tic tac toe game, and it works fine when the first X or O is inputted, but when the second is inputted the previous X or O is deleted and the new one is put in. I have no idea why this is happening.
import java.util.Scanner;
public class Play {
public static void main(String[] args){
Scanner kbd=new Scanner(System.in);
TicTacToeBoard t=new TicTacToeBoard(3, 3);
t.startBoard();
XO xo1=new XO();
xo1.setTurns(1);
XO xo2=new XO();
xo2.setTurns(0);
System.out.println("Player 1, what is your name?");
String n1=kbd.nextLine();
System.out.println("Player 2, what is your name?");
String n2=kbd.nextLine();
System.out.println(t);
while(!t.winner()&&!t.full()){
if(t.getTurnCnt()%2==0){
System.out.println(n1+"(X): ");
int x1=kbd.nextInt();
int y1=kbd.nextInt();
t.add(x1, y1, xo1);
System.out.println(t);
}
//this is where the board resets
else{
System.out.println(n2+"(O): ");
int x2=kbd.nextInt();
int y2=kbd.nextInt();
t.add(x2, y2, xo2);
System.out.println(t);
}
TicTacToeBoard Class:
public class TicTacToeBoard extends Board{
private XO[][] board;
private int turnCnt;
public TicTacToeBoard(int r, int c){
super(r, c);
board=new XO[r][c];
turnCnt=0;
}
public void startBoard(){
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
board[i][j]=new XO();
board[i][j].setName("-");
}
}
}
public void setTurnCnt(int t){
turnCnt=t;
}
public XO[][] setBoard(XO[][] b){
return b;
}
public XO[][] getBoard(){
return board;
}
public int getTurnCnt(){
return turnCnt;
}
public boolean add(int x, int y, XO x1){
if(x<=this.getRows()&&y<=this.getCols()&&(board[x-1][y-1].getName().equals("-"))){
board[x-1][y-1].setName(x1.getName());
turnCnt++;
return true;
}
else
System.out.println("error");
return false;
}
public boolean winner(){
boolean t=false;
for(int i=0;i<3;i++){
if(board[i][0].equals(board[i][1], board[i][2])||board[0][i].equals(board[1][i], board[2][i])||board[0][0].equals(board[1][1], board[2][2])||board[2][0].equals(board[1][1], board[0][2]))
t=true;
}
return t;
}
public boolean XWinner(){
boolean t=false;
for(int i=0;i<3;i++){
if((board[i][0].equals(board[i][1], board[i][2])&&board[i][1].getName().equals("X"))||(board[0][i].equals(board[1][i], board[2][i])&&board[0][i].getName().equals("X"))||(board[0][0].equals(board[1][1], board[2][2])&&board[0][0].getName().equals("X"))||(board[2][0].equals(board[1][1], board[0][2])&&board[2][0].getName().equals("X")))
t=true;
}
return t;
}
public boolean full(){
boolean t=true;
for(int r=0;r<3;r++){
for(int c=0;c<3;c++){
if(board[r][c].getName()=="-")
t=false;
}
}
return t;
}
public String toString(){
return "\t\t\tCol\n\t\t1\t2\t3\nRow\t1\t"+board[0][0]+"\t"+board[0][1]+"\t"+board[0][2]+"\n\t2\t"+board[1][0]+"\t"+board[1][1]+"\t"+board[1][2]+"\n\t3\t"+board[2][0]+"\t"+board[2][1]+"\t"+board[2][2];
}
}
XO class:
public class XO {
private String name;
private int turn;
public XO(){
turn=-1;
}
public int getTurns(){
return turn;
}
public String getName(){
if(this.getTurns()==1)
name="X";
else if(this.getTurns()==0)
name="O";
else
name="-";
return name;
}
public void setName(String n){
name=n;
}
public void setTurns(int t){
turn=t;
}
public boolean equals(XO x1, XO x2){
if (x1.getName().equals(this.getName())&&x2.getName().equals(this.getName())&&this.getName()!="-")
return true;
else
return false;
}
public String toString(){
return name;
}
}
The problem is on your function
public String getName(){
if(this.getTurns()==1)
name="X";
else if(this.getTurns()==0)
name="O";
else
name="-";
return name;
}
Every time is called the name field is updated despite it is a getter method! This is not a best practice.
Let's go step by step:
the user gives his coordinates.
the name is set to the correct value: "X" or "O"
the board is printed (calling XO.toString (using name field direct
no through any getter
The status of the board is evaluated using the getName getter and
now is when the name got back to "-" because the turn has not been
changed.
Finally, I think that you can simplify XO class. Turn field does not add any worth. It seems enough to use the name field itself. And the if statement is redundant because the boolean expression inside the if is just what you want to return.
class XO {
String name="-";
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
public boolean equals(XO x1, XO x2){
return(x1.getName().equals(this.getName())&&x2.getName().equals(this.getName())&&this.getName()!="-");
}
#Override
public String toString() {
return getName();
}
}
As an example, this can be the final code. Notice that more refactor can be done i.e. use an enum for XO status.
import java.util.Scanner;
public class Play {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
TicTacToeBoard t = new TicTacToeBoard(3, 3);
t.startBoard();
XO xo1 = new XO();
xo1.setName("O");
XO xo2 = new XO();
xo2.setName("X");
System.out.println("Player 1, what is your name?");
String n1 = kbd.nextLine();
System.out.println("Player 2, what is your name?");
String n2 = kbd.nextLine();
System.out.println(t);
while (!t.winner() && !t.full()) {
if (t.getTurnCnt() % 2 == 0) {
System.out.println(n1 + "(X): ");
int x1 = kbd.nextInt();
int y1 = kbd.nextInt();
t.add(x1, y1, xo1);
System.out.println(t);
}
//this is where the board resets
else {
System.out.println(n2 + "(O): ");
int x2 = kbd.nextInt();
int y2 = kbd.nextInt();
t.add(x2, y2, xo2);
System.out.println(t);
}
}
}
}
class TicTacToeBoard {
private XO[][] board;
private int turnCnt;
public TicTacToeBoard(int r, int c){
board=new XO[r][c];
turnCnt=0;
}
public void startBoard(){
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
board[i][j]=new XO();
board[i][j].setName("-");
}
}
}
public void setTurnCnt(int t){
turnCnt=t;
}
public XO[][] setBoard(XO[][] b){
return b;
}
public XO[][] getBoard(){
return board;
}
public int getTurnCnt(){
return turnCnt;
}
public boolean add(int x, int y, XO x1){
if(x<=this.getRows()&&y<=this.getCols()&&(board[x-1][y-1].getName().equals("-"))){
board[x-1][y-1].setName(x1.getName());
turnCnt++;
return true;
}
else
System.out.println("error");
return false;
}
public boolean winner(){
boolean t=false;
for(int i=0;i<3;i++){
if(board[i][0].equals(board[i][1], board[i][2])||board[0][i].equals(board[1][i], board[2][i])||board[0][0].equals(board[1][1], board[2][2])||board[2][0].equals(board[1][1], board[0][2]))
t=true;
}
return t;
}
public boolean XWinner(){
boolean t=false;
for(int i=0;i<3;i++){
if((board[i][0].equals(board[i][1], board[i][2])&&board[i][1].getName().equals("X"))||(board[0][i].equals(board[1][i], board[2][i])&&board[0][i].getName().equals("X"))||(board[0][0].equals(board[1][1], board[2][2])&&board[0][0].getName().equals("X"))||(board[2][0].equals(board[1][1], board[0][2])&&board[2][0].getName().equals("X")))
t=true;
}
return t;
}
public boolean full(){
boolean t=true;
for(int r=0;r<3;r++){
for(int c=0;c<3;c++){
if(board[r][c].getName()=="-")
t=false;
}
}
return t;
}
public String toString(){
return "\t\t\tCol\n\t\t1\t2\t3\nRow\t1\t"+board[0][0]+"\t"+board[0][1]+"\t"+board[0][2]+"\n\t2\t"+board[1][0]+"\t"+board[1][1]+"\t"+board[1][2]+"\n\t3\t"+board[2][0]+"\t"+board[2][1]+"\t"+board[2][2];
}
public int getRows() {
return 3;
}
public int getCols() {
return 3;
}
}
class XO {
String name="-";
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
public boolean equals(XO x1, XO x2){
return(x1.getName().equals(this.getName())&&x2.getName().equals(this.getName())&&this.getName()!="-");
}
#Override
public String toString() {
return getName();
}
}

using Adjacency list structure for directed graph 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
}

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());
}

Categories