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.
Related
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);
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
}
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. ;)
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());
}
I use centralized patter to coding vending machine. The problem is I found out that I cannot change states. In the constructor, I initialized state to Ls[0], but when I go to the method public void coin() to change the state, I found that the state doesn't changed. The part of my code is:
class Vending_machine {
State st;
private int price;
private int k;
private int k1;
private int t;
private int s;
private State[] Ls;
public Vending_machine() {
Ls = new State[7];
Ls[0] = new Idle();
Ls[1] = new Coins_inserted();
Ls[2] = new Sugar();
Ls[3] = new No_small_cups();
Ls[4] = new No_large_cups();
Ls[5] = new Exit();
Ls[6] = new Start();
st = Ls[0];
st.vm = this;
k = 0;
k1 = 0;
t = 0;
price = 0;
s = 0;
}
public void setK(int k) {
this.k = k;
}
public int getK() {
return k;
}
public void setS(int s) {
this.s = s;
}
public int getS() {
return s;
}......
public void coin() {
st.coin();
if (st.getId() == 0) {
if (t + 25 < price) {
// t=t+25;
st = Ls[0];
}
if (t + 25 >= price && price > 0) {
// s=0;
// t=0;
st = Ls[1];
}
}......
class State {
public Vending_machine vm;
int id = 0;
public void coin() {}
public void small_cup() {}
public void large_cup() {}
public void sugar() {}
public void tea() {}
public void insert_large_cups(int n) {}
public void insert_small_cups(int n) {}
public void set_price(int p) {}
.......
}
class Idle extends State {
public void coin() {
if (vm.getT() + 25 < vm.getPrice()) {
vm.setT((vm.getT()) + 25);
System.out.println(vm.getT());
}
else if ((vm.getT() + 25 >= vm.getPrice()) && (vm.getPrice() > 0)) {
vm.setS(0);
vm.setT(0);
}
}......