I am trying to convert some java code to c++, however, I am having an issue with java's list.add versus c++ list.insert. Here is the java code that I've started to convert:
public class SimulationQueue {
private String arrivalFilePath;
private int currentTime;
private class Event {
private boolean arrival;
private int start;
private int span;
public Event() {
this.arrival = true;
this.start = 0;
this.span = 0;
}
public Event(boolean isArrival, int startTime, int span) {
this.arrival = isArrival;
this.start = startTime;
this.span = span;
}
public int at() { return start; }
public boolean isArrival() { return arrival; }
public int duration() { return span; }
public void getArrivalEvent(Scanner arrivalFile) {
this.arrival = true;
this.start = arrivalFile.nextInt();
this.span = arrivalFile.nextInt();
}
}
public SimulationQueue(String arrivalFilePath) {
this.arrivalFilePath = arrivalFilePath;
this.currentTime = 0;
}
private void addEventToList(Event event, List<Event> eventList) {
if (eventList.isEmpty()) eventList.add(0, event);
else if (eventList.get(0).at() < event.at()) eventList.add(event);
else eventList.add(0, event);
}
And here is the so far converted c++ version:
struct EventList {
bool arrival;
int start, span, currentTime;
string arrivalFilePath;
EventList(bool isArrival, int startTime, int span);
void getArrivalEvent(istream& arrivalFile);
void simulationQueue (string arrivalFilePath);
void addEventToList(EventList& event, list<EventList> eventList);
void simulate();
EventList() {
this->arrival = true;
this->start = 0;
this->span = 0;
}
int at() {
return start;
}
bool isArrival() {
return arrival;
}
int duration() {
return span;
}
};
EventList::EventList(bool isArrival, int startTime, int span) {
this->arrival = isArrival;
this->start = startTime;
this->span = span;
}
void EventList::getArrivalEvent(istream& arrivalFile) {
this->arrival = true;
int first = this->start;
int duration = this->span;
arrivalFile >> first;
arrivalFile >> duration;
}
void EventList::simulationQueue (string arrivalFilePath) {
this->arrivalFilePath = arrivalFilePath;
this->currentTime = 0;
}
void EventList::addEventToList(EventList& event, list<EventList> eventList) {
if (eventList.empty())
}
I'm not very experienced so I know I'm probably approaching this wrong but it's compiling alright. The issue I have is with:
void EventList::addEventToList(EventList& event, list<EventList> eventList) {
if (eventList.empty())
}
I don't know how to convert this part to c++:
private void addEventToList(Event event, List<Event> eventList) {
if (eventList.isEmpty()) eventList.add(0, event);
else if (eventList.get(0).at() < event.at()) eventList.add(event);
else eventList.add(0, event);
}
If I write something like event.insert(event, 0) then it won't fit the parameters that insert takes.
You can just use list::push_back.
void EventList::addEventToList(EventList& event, list<EventList> eventList) {
eventList.push_back(event);
}
However, if you leave it just like that, the calling function won't see the new item in the list since you passed eventList to the function by value. You need to pass it by reference.
void EventList::addEventToList(EventList& event, list<EventList>& eventList) {
eventList.push_back(event);
}
list::push_back adds items to the end (back) of the list. If you'd rather add the item at the start (front) of the list, you can use list::push_front.
void EventList::addEventToList(EventList& event, list<EventList>& eventList) {
eventList.push_front(event);
}
Related
else if(left || right) {
if(currentAction != WALKING) {
currentAction = WALKING;
animation.setFrames(sprites.get(WALKING));
animation.setDelay(40);
width = 30;
Here is the code I am having issues with. namely the animation.setFrames and setDelay the setFrames uses a BufferedImage array and the setDelay is a long variable. The two errors that come up are
The method setFrames(BufferedImage[]) is undefined for the type Animation
and
The method setDelay(Duration) in the type Animation is not applicable for the arguments (int)
public void setFrames(BufferedImage[] frames) {
this.frames = frames;
currentFrame = 0;
startTime = System.nanoTime();
playedOnce = false;
this is the code for the setFrames and the code of delay's setter is just
public void setDelay(long d) {
delay = d;
}
Any assistance is welcome.
There were none of these errors in the tutorial
EDIT: I have created a new Animation class in the constructor but it did not solve it. Added Animation class
package Entity;
import java.awt.image.BufferedImage;
public class Animation {
private BufferedImage[] frames;
private int currentFrame;
private long startTime;
private long delay;
private boolean playedOnce; played; e.g. an attack so it does not
public void Animation() {
playedOnce = false;
}
public void setFrames(BufferedImage[] frames) {
this.frames = frames;
currentFrame = 0;
startTime = System.nanoTime();
playedOnce = false;
}
public void setDelay(long d) {
delay = d;
}
public void setFrame(int i) {
currentFrame = i;
}
public void update() {
if (delay == -1)
return;
long elapsed = (System.nanoTime() - startTime) / 1000000;
if (elapsed > delay) {
currentFrame++;
playedOnce = true;
}
}
public int getFrame() {
return currentFrame;
}
public BufferedImage getImage() {
return frames[currentFrame];
}
public boolean hasPlayedOnce() {
return playedOnce;
}
}
Thank you to Bandreid for the answer.
It need the object to be added and a new object created.
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 am trying allready to make custome model for JSpinner but it doesnt work.
the code looks like:
public class ModelJSpinner implements SpinnerModel
{
private long value;
private long min;
private long max;
private long increment;
private ChangeListener l;
private ArrayList<ChangeListener> listeners;
#Override
public Object getValue()
{
return null;
}
public ModelJSpinner(long min, long max, long increment)
{
super();
this.min = min;
this.max = max;
this.increment = increment;
setValue(min);
listeners = new ArrayList<>();
}
#Override
public void setValue(Object value)
{
if (value == null)
{
}else {
this.value = (Long) value;
}
//fireStateChanged();
}
private void fireStateChanged()
{
if (listeners == null)
return;
for (int a = 0; a < listeners.size(); a++)
{
ChangeListener l = (ChangeListener) listeners.get(a);
try
{
l.stateChanged(new ChangeEvent(this));
}
catch (RuntimeException e)
{
e.printStackTrace();
}
}
}
#Override
public Object getNextValue()
{
Long nextValue = value + increment;
if (nextValue > max)
{
return null;
}
else
{
return nextValue;
}
}
#Override
public Object getPreviousValue()
{
Long previousValue = value - increment;
if (previousValue < min)
{
return null;
}
else
{
return previousValue;
}
}
#Override
public void addChangeListener(javax.swing.event.ChangeListener l)
{
this.l = l;
listeners.add(l);
}
#Override
public void removeChangeListener(javax.swing.event.ChangeListener l)
{
if (this.l == l)
{
l = null;
}
listeners.add(l);
}
}
However when i run the following code i get...nothing much except JSpinner that doesnt do much...
public class Test
{
public static void main(String[] args)
{
ModelJSpinner model = new ModelJSpinner(10L, 20L, 5L);
JSpinner spinner = new JSpinner(model);
spinner.setModel(model);
spinner.setValue(15L);
JFrame frame = new JFrame("adasasd");
frame.setSize(350, 150);
frame.add(spinner);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
}
}
At the beginning, all i wanted was just to see that JSpinner can do something with above mentioned Model and later i wanted to implement Changelisteners.
As of now, i am not even able to have it drawn properly. Is there a chance that somebody could help me?
I need to use instance of Class implementing SpinnerModel as model for JSpinner and i just cannot make it work.
BR
DK
This is a guarantee to fail:
#Override
public Object getValue()
{
return null;
}
since this is the method that the JSpinner uses to determine what value to display.
Instead have this return the value held by your value field. Also, don't return null for the getNextValue() if next value is above max. Instead return the max. Similarly for the getPreviousValue(), return the min value if the calculated previous value is less than min.
For example,
public class SpinnerModel3 implements SpinnerModel {
private long value;
private long min;
private long max;
private long increment;
// using a set to avoid allowing addition of duplicate listeners
private Set<ChangeListener> listenerSet = new HashSet<>();
public SpinnerModel3(long value, long min, long max, long increment) {
super();
this.value = value;
this.min = min;
this.max = max;
this.increment = increment;
}
#Override
public void addChangeListener(ChangeListener l) {
listenerSet.add(l);
}
#Override
public Object getNextValue() {
long nextValue = value + increment;
nextValue = Math.min(nextValue, max);
return nextValue;
}
#Override
public Object getPreviousValue() {
long prevValue = value - increment;
prevValue = Math.max(prevValue, min);
return prevValue;
}
#Override
public Object getValue() {
return value;
}
#Override
public void removeChangeListener(ChangeListener l) {
listenerSet.remove(l);
}
#Override
public void setValue(Object value) {
this.value = (long) value;
fireStateChanged();
}
protected void fireStateChanged() {
// create a ChangeEvent object
ChangeEvent e = new ChangeEvent(this);
for (ChangeListener l : listenerSet) {
l.stateChanged(e); // notify all listeners
}
}
}
Note that it is usually better to use the extend the abstract model class if one is available (or even better, the default model class, but none is available for spinner model). So better still:
#SuppressWarnings("serial")
public class SpinnerModel2 extends AbstractSpinnerModel {
private long value;
private long min;
private long max;
private long increment;
public SpinnerModel2(long value, long min, long max, long increment) {
super();
this.value = value;
this.min = min;
this.max = max;
this.increment = increment;
}
#Override
public Object getNextValue() {
long nextValue = value + increment;
nextValue = Math.min(nextValue, max);
return nextValue;
}
#Override
public Object getPreviousValue() {
long prevValue = value - increment;
prevValue = Math.max(prevValue, min);
return prevValue;
}
#Override
public Object getValue() {
return value;
}
#Override
public void setValue(Object value) {
this.value = (long) value;
fireStateChanged();
}
}
Ok I will try to make this clear as possible. I hope it doesn't get flagged before I get an answer.
I am trying to serialize a class for saving which works just fine. But some of the variables are not getting loaded correctly. Here is the code:
I also marked out places where the code is working and not working.
EDIT: Simplified code a bit more.
Class im saving: (Simple version of it)
public class classToSave implements Serializable {
/**
*
*/
private static final long serialVersionUID = -5184436214950145051L;
public static List<classToSave> classtosavelist = new ArrayList<classToSave>();
public static classToSave one = new OtherClass1("1", 1, 1, null, Item.1, 1);
public static classToSave two = new OtherClass1("2", 1, 2, one , Item.2, 1);
public static classToSave three = new OtherClass2("3", 1, 4, two , Item.3, 2);
public boolean done = false; < WONT LOAD/SAVE
public int lvl = 0; < WONT LOAD/SAVE
transient protected String name; < OK
protected int Xpos; < OK
protected int Ypos; < OK
public Skill parent; < OK
protected Item item; < OK
public int extra = 0; < OK (This Works..)
public classToSave(String s, int x, int y, Skill parent, Item item, int cost) {
this.name = s;
this.Xpos = x;
this.Ypos = y;
if(parent != null) {
this.Xpos += parent.Xpos;
this.Ypos += parent.Ypos;
}
this.parent = parent;
this.item = item;
add(this, s);
}
private void add(classToSave classtosave, String name) {
boolean flag = true;
for(int i = 0; i < skills.size(); i++) {
if(classtosavelist.get(i).getName().equalsIgnoreCase(name)) {
flag = false;
}
}
if(flag) {
classtosavelist.add(classtosave);
}
}
public int needPoints() {
return 1 + extra;
}
public boolean Done(int points) {
if(points >= needPoints()) {
this.done = true;
}
return this.done;
}
public int getLevel() {
return this.lvl;
}
public int MAXLevel() {
return 1;
}
public void LevelUp() {
if(this.lvl < MAXLevel()) {
this.lvl++;
}
}
public void Reset() {
this.lvl = 0;
}
public Item getRenderItem() {
return this.item;
}
public String getName() {
return this.name;
}
public Skill getParent() {
return this.parent;
}
public boolean isCompleteDone() {
return (getLevel() == MAXLevel() && done);
}
Here is the save and load:
private ClassToSave classtosave;
private void save(String savename) {
if (externalStorageWriteable) {
try {
File file = new File(ctxt.getExternalFilesDir(null), savename);
FileOutputStream fos = new FileOutputStream(file, false);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(classtosave);
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void load(String savename) throws ClassNotFoundException, StreamCorruptedException, IOException {
if (externalStorageAvailable) {
File file = new File(ctxt.getExternalFilesDir(null), savename);
FileInputStream fis = new FileInputStream(file);
ObjectInputStream is = new ObjectInputStream(fis);
ClassToSave classtosave = (ClassToSave) is.readObject();
for (int i=0; i < classtosave.classtosavelist.size(); i++) {
classtosave.classtosavelist.get(i).Done(classtosave.classtosavelist.get(i).needPoints()); < WORKS
classtosave.classtosavelist.get(i).isCompleteDone(); < DOENST WORK
classtosave.classtosavelist.get(i).getLevel(); < DOESNT WORK
if (classtosave.classtosavelist.get(i).done == true){ <DOESNT WORK
classtosave.classtosavelist.get(i).done = true;
classtosave.classtosavelist.get(i).LevelUp();
}
}
}
is.close();
}
Sorry if brackets are out of place. This code was butchered(Renamed and modified) to make it more readable.
But basically this code is used for a "Skill tree" and what it is supposed to do is save if said skill is complete or not.
If this needs fixed let me know. I can also provide more code as needed.
Your constructor misses the boolean and the int. It should be like this :
public classToSave(boolean done, int lvl, String s, int x, int y, Skill parent, Item
item, int cost) {
this.done = done;
this.lvl = lvl;
...
}
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());
}