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);
}
}......
Related
I have a graph that contains objects of type GraphNodes. These nodes contain an object City that has properties if It's infected or not. I want to loop through all the nodes and check if a city is infected or not. I have a generic method getInfo which returns an object of type E in my case City. But when i try to chain another method or to get property i can't see them as if they are not available. All the classes in the code are from college so i can't add/remove methods. I've tried with foreach but I still can't get the methods.
Code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.LinkedList;
class City {
String osnovna_granka;
boolean zarazen;
City(String osnovna_granka, boolean zarazen) {
this.osnovna_granka = osnovna_granka;
this.zarazen = zarazen;
}
#Override
public String toString() {
if (zarazen == true) {
return osnovna_granka + " zarazen";
} else {
return osnovna_granka + " nezarazen";
}
}
}
class Graph {
int num_nodes;
GraphNode<City> adjList[];
#SuppressWarnings("unchecked")
public Graph(int num_nodes) {
this.num_nodes = num_nodes;
adjList = (GraphNode<City>[]) new GraphNode[num_nodes];
}
int adjacent(int x, int y) {
// proveruva dali ima vrska od jazelot so
// indeks x do jazelot so indeks y
return (adjList[x].containsNeighbor(adjList[y])) ? 1 : 0;
}
void addEdge(int x, int y) {
// dodava vrska od jazelot so indeks x do jazelot so indeks y
if (!adjList[x].containsNeighbor(adjList[y])) {
adjList[x].addNeighbor(adjList[y]);
}
}
void deleteEdge(int x, int y) {
adjList[x].removeNeighbor(adjList[y]);
}
#Override
public String toString() {
String ret = new String();
for (int i = 0; i < this.num_nodes; i++) {
ret += i + ": " + adjList[i] + "\n";
}
return ret;
}
}
class GraphNode<E> {
private int index;//index (reden broj) na temeto vo grafot
private E info;
private LinkedList<GraphNode<E>> neighbors;
public GraphNode(int index, E info) {
this.index = index;
this.info = info;
neighbors = new LinkedList<GraphNode<E>>();
}
boolean containsNeighbor(GraphNode<E> o) {
return neighbors.contains(o);
}
void addNeighbor(GraphNode<E> o) {
neighbors.add(o);
}
void removeNeighbor(GraphNode<E> o) {
if (neighbors.contains(o)) {
neighbors.remove(o);
}
}
#Override
public String toString() {
String ret = "INFO:" + info + " SOSEDI:";
for (int i = 0; i < neighbors.size(); i++) {
ret += neighbors.get(i).info + " ";
}
return ret;
}
#Override
public boolean equals(Object obj) {
#SuppressWarnings("unchecked")
GraphNode<E> pom = (GraphNode<E>) obj;
return (pom.info.equals(this.info));
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public E getInfo() {
return info;
}
public void setInfo(E info) {
this.info = info;
}
public LinkedList<GraphNode<E>> getNeighbors() {
return neighbors;
}
public void setNeighbors(LinkedList<GraphNode<E>> neighbors) {
this.neighbors = neighbors;
}
}
public class Main {
public static void main(String[] args) throws Exception {
int i, j, k;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
Graph g = new Graph(N);
for (i = 0; i < N; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
st.nextToken();
String osnovna_granka = st.nextToken();
String str_zarazen = st.nextToken();
if (str_zarazen.equals("zarazen")) {
g.adjList[i] = new GraphNode(i, new City(osnovna_granka, true));
} else {
g.adjList[i] = new GraphNode(i, new City(osnovna_granka, false));
}
}
int M = Integer.parseInt(br.readLine());
for (i = 0; i < M; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
g.addEdge(a, b);
g.addEdge(b, a);
}
br.close();
Stack<GraphNode> stack = new Stack<>();
int counter = 0;
// vasiot kod ovde;
for(GraphNode gn: g.adjList) {
gn.getInfo().// Here the properties of City should show up
}
}
}
GraphNode is a generic type and you have not specified the type, the IDE cannot infer the type so no methods can be suggested. in the for loop you need to specify the type of the GraphNode.
for(GraphNode<City> gn: g.adjList)
My question is if it possible to use a void method in a setText for a Label? I'm working at the moment on school homework on Netbeans and I want to use the 'public void printTable()' in a Label but the programm always say that it is impossible to use a void here and I know that normally I should use a return statement but in the instruction is written that I should use a 'void'.
Here you can see my Java Class
public class AffineFunction
{
private int a;
private int b;
public int getA()
{
return a;
}
public int getB()
{
return b;
}
public void setA(int newA)
{
a = newA;
}
public void setB(int newB)
{
b = newB;
}
public AffineFunction(int pA, int pB)
{
a = pA;
b = pB;
}
public int solve(int x)
{
return (a*x)+b;
}
public void printTable()
{
for(int i =-10; i<=10; i++)
{
System.out.println("F(" + i + ") = " + solve(i));
}
}
public void printTable(double step)
{
for(double i = - 10 ; i<= 10; i = i + step)
{
System.out.println( "F(" + i + ") = " + solve((int)i));
}
}
}
Here is a part of my JFrame :
//E
int a = Integer.valueOf(aTextField.getText());
int b = Integer.valueOf(bTextField.getText());
int x = Integer.valueOf(xTextField.getText());
//T
AffineFunction affineFunction = new AffineFunction(a, b);
//S
FLabel.setText(String.valueOf(affineFunction.solve(x)));
printTableLabel.setText(String.valueOf(affineFunction.printTable()));
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);
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.
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.