Can I use a void method with a label.setText? - java

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

Related

Can't access the object within the GraphNode

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)

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

wrapping around minutes into hours

I'm doing simple clock which wraps around when reaching 0 (e.g 00:59 -> 01:00, 23:59 -> 00:00). I got stuck at this moment and can't figure it out.
I have to do this in this way, using just methods given in 'BoundedCounter' class.
public class Test3 {
public static void main(String[] args) {
BoundedCounter minutes = new BoundedCounter(59, 0);
BoundedCounter hours = new BoundedCounter(23, 0);
int i = 0;
while (i < 70) { //repeats actual time 70 times - just to check if works fine
//put code here
i++;
}
}
}
.
import java.text.DecimalFormat;
public class BoundedCounter {
private int startValue;
private int upperLimit;
private int value;
public BoundedCounter(int upperLimit, int startValue) {
this.upperLimit = upperLimit;
this.startValue = startValue;
this.value = startValue;
}
public void next() {
value++;
if (value > upperLimit) {
value = 0;
}
}
public String toString() {
DecimalFormat df = new DecimalFormat("#00");
return "" + df.format(value);
}
}
One variant is to use handlers:
import java.text.DecimalFormat;
public class Test3 {
public static void main(String[] args) {
final BoundedCounter minutes = new BoundedCounter(59, 0);
final BoundedCounter hours = new BoundedCounter(23, 0);
minutes.setOverflow(hours::next);
hours.setOverflow(minutes::reset);
for (int i = 0; i < 70; i++) { //repeats actual time 70 times - just to check if works fine
minutes.next();
System.out.println(hours.toString() + ":" + minutes.toString());
}
}
public static class BoundedCounter {
private int startValue;
private int upperLimit;
private int value;
private Runnable c;
public BoundedCounter(int upperLimit, int startValue) {
this.upperLimit = upperLimit;
this.startValue = startValue;
this.value = startValue;
}
public void reset() {
this.value = startValue;
}
public void setOverflow(final Runnable c) {
this.c = c;
}
public void next() {
if (++value > upperLimit) {
value = 0;
c.run();
}
}
public String toString() {
DecimalFormat df = new DecimalFormat("#00");
return "" + df.format(value);
}
}
}
Maybe this will help... To show current time use:
System.out.println(hours.toString() + ":" + minutes.toString());
To increment hours: hours.next()
To increment minutes: minutes.next()

java.lang.NullPointerException at com.rs.game.player.Dm.initiative(Dm.java:27) [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I just cannot figure out why this keeps pointing to null. I am a fairly new programmer. But here I have made a Dice class and a commands class.
I have tried changing variables and all sorts of stuff. I guess I'm just not sure why it's pointing to null.
package com.rs.game.player;
/**
* Created by Kevinpro0 on 2/26/2015.
*/
public class Dice {
public int die2;
public int die3;
public int die4;
public int die6;
public int die8;
public int die10;
public int die12;
public int die14;
public int die16;
public int die18;
public static int die20;
public void d2() {
die2 = (int)(Math.random()*2) +1;
}
public void d3() {
die3 = (int)(Math.random()*3) +1;
}
public void d4() {
die4 = (int)(Math.random()*4) +1;
}
public void d6() {
die6 = (int)(Math.random()*6) +1;
}
public void d8() {
die8 = (int)(Math.random()*8) +1;
}
public void d10() {
die10 = (int)(Math.random()*10) +1;
}
public void d12() {
die12 = (int)(Math.random()*12) +1;
}
public void d14() {
die14 = (int)(Math.random()*14) +1;
}
public void d16() {
die16 = (int)(Math.random()*16) +1;
}
public void d18() {
die18 = (int)(Math.random()*18) +1;
}
public static int d20() {
die20 = (int)(Math.random()*20) +1;
return die20;
}
}
/***** i am ONLY using d20 for this right now...****/
DM.java
package com.rs.game.player;
import com.rs.game.player.*;
import com.rs.game.World;
import java.util.Arrays;
/**
* Created by Kevinpro0 on 3/1/2015.
*/
public class Dm {
public static Dice init = new Dice();
public static int worldSize = World.getPlayers().size();
public static int[] PlayerInt = new int[worldSize];
//
public static Player player;
public static int initRoll = init.die20;
public static String playersName;
public static int i = 1;
public static void initiative(){
for (i = 1; i < World.getPlayers().size() + 1; i++) {
//Dice = new Dice();
init.d20();
PlayerInt[i] = initRoll;
player.getPackets().sendPanelBoxMessage(Integer.toString(Dice.d20()));
//player.getPackets().sendPanelBoxMessage("Player " + i + " is " + playersName + " and initiative roll: " + Integer.toString(initRoll));
}
}
}
Commands.java
case "init":
case "initiative":
Dm dmaster = new Dm();
//String currentPlayer = player.getUsername();
//Player Dm = World.getPlayerByDisplayName("Dm");
if (player.getUsername().equalsIgnoreCase("Dm")) {
if (World.getPlayers().size() <= 1){
player.getPackets().sendPanelBoxMessage("Not enough players logged in.");
} else {
Dm.initiative();
player.getPackets().sendPanelBoxMessage(Dm.playersName + " and initiative roll: " + Integer.toString(Dm.initRoll));
}
}
return true;
In this line public static int initRoll = init.die20; you are referring to the value of 'die20', but it is not set until much later, in the for loop, when you say init.d20(). I hope that helps a little, though I think your code needs work in other areas too.

transfer form one state to another

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

Categories