I don't event know how to describe this weird behaviour i'm dealing with right now, but the thing is:
I have a class Player.java that has a private float life, pretty basic.
this float has its setter / getter and there is NO other way of retrieving / attributing this variable without using the getter / setter.
also, i have put a println in each, so i can have a feedback of when this variable is being retrieved, and when is beign attributed, and i get THIS on my console:
my console
i don't think the stack trace is usefull in any way, but if you want to, i can paste the code behind the stack trace too
anyway, if you haven't notice, there is a retrieve of life = 61, FOLLOWED by a retriving of life = 70, with NO attribution WHATSOEVER of this variable back to 70.
also, i dont know if this is useful, but here is the code that prints the "1 damaged 0, broadcasting to clients - Sent":
it resume in:
- decreases the player life
- if it has died, mark as dead and do other little effect things
- send event to google analytics
- after all that, if the game is a server, broadcast the damage event to all clients
public void takeDamage(float amount, Player owner, boolean showBlood, boolean local){
if(local && KambojaMain.getInstance().multiplayerConnection && !KambojaMain.getInstance().isServer) return;
if(imunity <= 0){
//new Exception().printStackTrace();
setLife(getLife() - amount * def);
if(owner != null) {
owner.score += amount*def;
}
if(showBlood)
state.showBlood(body.getWorldCenter());
System.out.println(" - DAMAGE DETECTED from " + owner.getId() + " to " + getId() + " with value " + amount + ", it was a local? " + local + ", and show blood is: " + showBlood);
System.out.println("target life is now at " + getLife());
hitTimer = 1f;
if(getLife() <= 0){
if(!isDead()){
deaths++;
if(owner != null){
owner.kills ++;
owner.ghosts.add(new Ghost(getId(), getPosition()));
owner.score += 100;
}
setDead(true);
body.getFixtureList().get(0).setSensor(true);
getState().showSkull(body.getWorldCenter(), getAngle());
String playerType = "controller";
if(isKeyboard()) {
playerType = "keyboard";
}
if(this instanceof BetterBot) {
playerType = "bot";
}
HashMap<String, String> customs = new HashMap<String, String>();
customs.put("cd1", KambojaMain.getMapName());
customs.put("cd3", getWeapon().getClass().getSimpleName());
customs.put("cd4", "player_" + playerType);
String ow = "Suicide";
if(owner != null)
ow = owner.getWeapon().getClass().getSimpleName();
KambojaMain.event("game", "player_kill", ow, customs);
}
}
if(gruntTimer < 0){
if(GameState.SFX)
grunt[(int)(Math.random()*5)].play();
gruntTimer = 0.5f;
}
if(KambojaMain.getInstance().multiplayerConnection && KambojaMain.getInstance().isServer) {
KambojaPacket kp = new KambojaPacket(PacketType.PLAYER_DAMAGE);
PlayerDamage pd = new PlayerDamage();
pd.damage = amount;
pd.showBlood = showBlood;
pd.owner = owner.getId();
pd.target = getId();
kp.data = pd;
System.out.print(pd.owner + " damaged " + pd.target + ", broadcasting to clients - ");
KambojaMain.getInstance().broadcast(kp, Protocol.TCP);
System.out.println("Sent");
}
}
}
note: i AM using multi threading environment because this is a lan multiplayer game, and this variable can be retrieved in other threads different from the main thread.
I have searched about the volatile keyword, Atomic classes (AtomicFloat dont exist, and the implementation of it using AtomicInt as a bit data also was used), but none of this could prevent this from happening and i have NO idea of what is this behaviour and what is causing it
can someone please help me? i don't know what to search anymore
Try making your method synchronized (this would make sure only one thread can be running this method, on an instance of your class).
public synchronized void takeDamage(.... // same as before
Check out this post, it has a similar question with more info about running blocks of code atomically.
Related
I've decided to programm a search system for finding students and teachers in a school via GUI. It is an OOP and need some tweaking here and there, but there is one issue which doesn't seem logical to me. When I'm searching for a teacher, I have to type there name or surname into a JTextField and press the Search button which runs a method that loops through an ArrayList of teacher-objects and checks if their names match with the one in the Textfield. Then it checks if these teachers have multiple subjects and grades and it goes through nested if-statements. After the teacher is found, their information is displayed on a GUI with several Texfields. Theoretically if the name I typed into the TextField doesn't match one from the teacher objects, a Error Message should pop-up saying the teacher I'm looking for isn't in the system. But even though I type in the correct name and get all the information displayed, it sends me to the Error Message everytime. I tried to fix it with a break statement but that didn't work either. Can someone please help me with this.
Here is the code I'm talking about:
public void lehrerSuche()
{
String lehrername = tfSuchfeldLehrer.getText();
for(int i = 0; i < td.getFachliste(0).getListenLaengeLehrerListe();i++)
{
if(td.getFachliste(0).getLehrerliste(i).getName().equals(lehrername) || td.getFachliste(0).getLehrerliste(i).getNachname().equals(lehrername))
{
if(td.getFachliste(0).getLehrerliste(i).isMehrerefaecher() && td.getFachliste(0).getLehrerliste(i).isMehrereklassen())
{
tfNameLehrer.setText(td.getFachliste(0).getLehrerliste(i).getName() + " " + td.getFachliste(0).getLehrerliste(i).getNachname());
tfKürzelLehrer.setText(td.getFachliste(0).getLehrerliste(i).getKuerzel() + ".");
tfKlasse_1Lehrer.setText(td.getFachliste(0).getLehrerliste(i).getKlasse().getBezeichnung());
tfKlasse_2Lehrer.setText(td.getFachliste(0).getLehrerliste(i).getKlass2().getBezeichnung());
tfFach_1Lehrer.setText(td.getFachliste(0).getLehrerliste(i).getFach().getFachbezeichnung());
tfFach_2Lehrer.setText(td.getFachliste(0).getLehrerliste(i).getFach2().getFachbezeichnung());
}
if(td.getFachliste(0).getLehrerliste(i).isMehrerefaecher() == false && td.getFachliste(0).getLehrerliste(i).isMehrereklassen())
{
tfNameLehrer.setText(td.getFachliste(0).getLehrerliste(i).getName() + " " + td.getFachliste(0).getLehrerliste(i).getNachname());
tfKürzelLehrer.setText(td.getFachliste(0).getLehrerliste(i).getKuerzel() + ".");
tfKlasse_1Lehrer.setText(td.getFachliste(0).getLehrerliste(i).getKlasse().getBezeichnung());
tfKlasse_2Lehrer.setText(td.getFachliste(0).getLehrerliste(i).getKlass2().getBezeichnung());
tfFach_1Lehrer.setText(td.getFachliste(0).getLehrerliste(i).getFach().getFachbezeichnung());
}
if(td.getFachliste(0).getLehrerliste(i).isMehrerefaecher() && td.getFachliste(0).getLehrerliste(i).isMehrereklassen()==false)
{
tfNameLehrer.setText(td.getFachliste(0).getLehrerliste(i).getName() + " " + td.getFachliste(0).getLehrerliste(i).getNachname());
tfKürzelLehrer.setText(td.getFachliste(0).getLehrerliste(i).getKuerzel() + ".");
tfKlasse_1Lehrer.setText(td.getFachliste(0).getLehrerliste(i).getKlasse().getBezeichnung());
tfFach_1Lehrer.setText(td.getFachliste(0).getLehrerliste(i).getFach().getFachbezeichnung());
tfFach_2Lehrer.setText(td.getFachliste(0).getLehrerliste(i).getFach2().getFachbezeichnung());
}
if(td.getFachliste(0).getLehrerliste(i).isMehrerefaecher() == false && td.getFachliste(0).getLehrerliste(i).isMehrereklassen()==false)
{
tfNameLehrer.setText(td.getFachliste(0).getLehrerliste(i).getName() + " " + td.getFachliste(0).getLehrerliste(i).getNachname());
tfKürzelLehrer.setText(td.getFachliste(0).getLehrerliste(i).getKuerzel() + ".");
tfKlasse_1Lehrer.setText(td.getFachliste(0).getLehrerliste(i).getKlasse().getBezeichnung());
tfFach_1Lehrer.setText(td.getFachliste(0).getLehrerliste(i).getFach().getFachbezeichnung());
}
break;
}
else
{
switchPanels_3(panelErrorLehrer);
}
}
}
I've uploaded my project to GitHub. Methods and variables are written in German, so I'm really sorry if you can't understand what I have written. If u have questions please hit me up. I use Eclipse to code.
This link should direct you to my GitHub:
https://github.com/Gonzo-CR/Home-Projects.git
If the link doesn't work, look for Gonzo-CR on GitHub and check out my Home-projects repository where I uploaded all the files.
For better undestanding these are the Object oriented classes:
Person(Abstract)
Schueler
Lehrer
Fach
Schulklasse
Spezial
Sprecher
GUI classes:
Suchsystem
Testdaten(A class which generates all my objects)
The problem is likely that if td.getFachliste(0).getLehrerliste(i).getName().equals(lehrername) is not true the very first time the loop runs, switchPanels_3(panelErrorLehrer); will be triggered - regardless of whether the condition is met on a later iteration of the loop.
What you need is to check a sentinel value after the loop finishes - e.g.:
bool lehrerGefunden = false;
for(int i = 0; i < td.getFachliste(0).getListenLaengeLehrerListe();i++){
if(td.getFachliste(0).getLehrerliste(i).getName().equals(lehrername) || td.getFachliste(0).getLehrerliste(i).getNachname().equals(lehrername)){
//etc.
lehrerGefunden = true;
break;
}
}
if(!lehrerGefunden){
switchPanels_3(panelErrorLehrer);
}
That way, you check every entry in the list before deciding whether to show the error.
My issue is with the following code. Eclipse IDE gives me no errors or warnings, yet when I print out a simple System.out.println("Test" + i);, I would get a running program up to the number 2509, or currently 2517 after rebooting Eclipse.
Essentially, I want to take an array of objects, say an array of "persons," and place them in random spots in another object array, say "bus stops." Assume that I have properly made the object arrays for "busStops and "people"
Yes, I realize that it defeats the purpose of making the "person" object as of yet, but that is something that can be included later.
Edit: Null values are simulated areas where people can't go, like a lake.
Edit2: replaced for with while loop, replaced decremented i with continue keyword.
Edit3: added more of the methods to elaborate the imperfections of my code. Then again, maybe most of it is good and I'm not understanding something important about loops.
private static void distributePeople() {
boolean temp = true;
int i = 0;
while (temp) {
// Select random points in array
int a = rand.nextInt(busStops.length);
int b = rand.nextInt(busStops[0].length);
// At random busStop, check if available and check if not full.
// If it is not full, place a person there.
if (busStops[a][b] == null) {
// if null, reset this run
continue;
} else {
if (busStops[a][b].isMaxPeople() == false) {
busStops[a][b].setNumberOfPeople(1);
i++;
System.out.println("Test: " + i);
} else {
// if true, reset this run
continue;
}
}
if (i == people.length) {
temp = false;
}
}
}
private static void setMaxPeopleAtBusStop() {
busStops[0][0].setMaxNumberOfPeople(1977 + 2);
busStops[1][0].setMaxNumberOfPeople(2 + 1643);
busStops[2][0].setMaxNumberOfPeople(1643 + 1201);
busStops[3][0].setMaxNumberOfPeople(1201 + 1267);
busStops[0][1].setMaxNumberOfPeople(366 + 0);
busStops[2][1].setMaxNumberOfPeople(0 + 797);
busStops[3][1].setMaxNumberOfPeople(797 + 34);
busStops[0][2].setMaxNumberOfPeople(1740 + 0);
busStops[2][2].setMaxNumberOfPeople(0 + 1444);
busStops[3][2].setMaxNumberOfPeople(1444 + 1963);
busStops[0][3].setMaxNumberOfPeople(839 + 1131);
busStops[1][3].setMaxNumberOfPeople(1131 + 1092);
busStops[2][3].setMaxNumberOfPeople(1092 + 912);
busStops[3][3].setMaxNumberOfPeople(912 + 1965);
busStops[0][4].setMaxNumberOfPeople(1552 + 1297);
busStops[1][4].setMaxNumberOfPeople(1297 + 1345);
busStops[2][4].setMaxNumberOfPeople(1345 + 614);
busStops[3][4].setMaxNumberOfPeople(614 + 1108);
busStops[0][5].setMaxNumberOfPeople(1490 + 228);
busStops[1][5].setMaxNumberOfPeople(228 + 187);
busStops[2][5].setMaxNumberOfPeople(187 + 906);
busStops[3][5].setMaxNumberOfPeople(906 + 36);
busStops[0][6].setMaxNumberOfPeople(634 + 1293);
busStops[1][6].setMaxNumberOfPeople(1293 + 0);
busStops[3][6].setMaxNumberOfPeople(0 + 1929);
busStops[0][7].setMaxNumberOfPeople(759 + 388);
busStops[1][7].setMaxNumberOfPeople(388 + 0);
busStops[3][7].setMaxNumberOfPeople(0 + 1149);
busStops[0][8].setMaxNumberOfPeople(1809 + 1880);
busStops[1][8].setMaxNumberOfPeople(1880 + 1979);
busStops[2][8].setMaxNumberOfPeople(1979 + 954);
busStops[3][8].setMaxNumberOfPeople(954 + 1332);
busStops[0][9].setMaxNumberOfPeople(1890 + 408);
busStops[1][9].setMaxNumberOfPeople(408 + 1771);
busStops[2][9].setMaxNumberOfPeople(1771 + 587);
busStops[3][9].setMaxNumberOfPeople(557 + 1961);
}
From the appropriate BusStop class:
static int MAX_PEOPLE_HERE;
public int setNumberOfPeople(int a) {
return numberOfPeopleHere += a;
}
protected boolean isMaxPeople() {
if (numberOfPeopleHere >= MAX_PEOPLE_HERE) {
return true;
} else {
return false;
}
}
public void setMaxNumberOfPeople(int a) {
MAX_PEOPLE_HERE = a;
}
Note: I should have a max number of 13000 people, which is smaller than the room available above.
Ok so your problem is that you're using a static variable for MAX_PEOPLE_HERE but you're trying to use it in a non static way. Thus ever time you call setMaxNumberOfPeople on any bus stop you set it for all bus stops.
This means that MAX_PEOPLE_HERE will end up being 557 + 1961 = 2518.
I'm guessing that numberOfPeopleHere is also static and thus you can only ever 2518 people to bus stops. If you try to do more than this then you'll end up with an infinite loop as you are seeing.
Change both MAX_PEOPLE_HERE (rename this to maxPeopleHere) and numberOfPeopleHere to local instance variables and I suspect everything will start working.
Use continue instead of i-- to skip current iteration. As #Hovercraft Full Of Eels stated, you've got infinite loop because of index modification within the loop
This one should be fairly simple I think, I just can't remember how, when using get methods of an object, how to pull the highest double out of the pack and put it in the println.
So far I just get every object to print with its percentages. But for the life of me I just can't remember and I know I've done this before.
public void displayBookWithBiggestPercentageMarkup(){
Collection<Book> books = getCollectionOfItems();
Iterator<Book> it = books.iterator();
while(it.hasNext()){
Book b = it.next();
double percent = b.getSuggestedRetailPriceDollars() / b.getManufacturingPriceDollars() * 100.0;
System.out.println("Highest markup is " + percent + " " + b.getTitle() + " " + b.getAuthor().getName().getLastName());
}
}
I'm pretty sure I need another local variable but I can't seem to do anything but make it equal the other percent. I have removed the other variable for now as I try to think about it.
I won't go into a lot of detail because it's homework (well done for being up-front about that, by the way) but here's the key idea: keep track of the largest percentage you've seen so far as your loop runs. That's what you want in your other variable.
Good job posting what you've tried so far. You were on the right track. As you loop through your books, keep a variables continuously updated with the highest percent seen so far and another variable for the associated book. Output the variable at the end outside the loop after iteration is done. Also, don't forget to check the edge case of an empty list of books! Something like this should do the trick:
public void displayBookWithBiggestPercentageMarkup(){
Collection<Book> books = getCollectionOfItems();
if (books.size() == 0) {
return;
}
Iterator<Book> it = books.iterator();
double highestPercent = 0;
Book highestPercentBook = null;
while(it.hasNext()){
Book b = it.next();
double percent = b.getSuggestedRetailPriceDollars() / b.getManufacturingPriceDollars() * 100.0;
if (percent > highestPercent) {
highestPercent = percent;
highestPercentBook = b;
}
}
System.out.println("Highest markup is " + highestPercent
+ " " + highestPercentBook.getTitle()
+ " " + highestPercentBook.getAuthor().getName().getLastName());
}
Alright so I'm currently writing some code for a project I'm working on, and I decided an Enum for data storage will be my best bet. But in the first time in my life, the enum.ordinal() returns -1?
Heres the code:
DuelRules.Rules rule = DuelRules.Rules.values()[(buttonId - (buttonId < 29 ? 18 : 19))];
if (buttonId == 29) {
rule = DuelRules.Rules.POCKET;
}
System.out.println(rule + ", " + rule.ordinal());
rules.swapRule(player, other, rule);
reset(false);
This statement here:
System.out.println(rule + ", " + rule.ordinal());
It prints the correct rule value, but when it prints rule.ordinal() it is printing -1?
Example:
HAT, -1
My Enum:
public enum Rules {
HAT(5000, 1),
CAPE(5000, 2),
AMULET(5000, 4),
WEAPON(5000, 8),
BODY(5000, 16),
SHIELD(5000, 32),
LEG(5000, 128),
GLOVE(5000, 512),
BOOT(5000, 1024),
RING(5000, 4096),
ARROW(5000, 8192),
POCKET(17837, 1),
FORFEIT(4989),
MOVEMENT(4990),
RANGE(4991),
MELEE(4992),
MAGIC(4993),
DRINKS(4994),
FOOD(4995),
PRAYER(4996),
OBSTACLES(4997),
FUN_WEAPONS(4998),
NO_ABILITIES(4999),
SUMMONING(5001);
private final int varbitId;
private final int value;
private Rules(int id, int... value) {
this.varbitId = id;
this.value = value.length > 0 ? value[0] : 0;
}
}
Note, that enum is inside of another class, not sure if that can effect the outcome. Thanks for your help, I'm completely lost with this one.
EDIT: Upon farther review I found that the ordinal is being changed by passing it as an argument?
Screnshot of console:
Code:
} else if (buttonId >= 18 && buttonId <= 42) {
DuelRules.Rules rule = DuelRules.Rules.values()[(buttonId - (buttonId < 29 ? 18 : 19))];
System.out.println("Point one: "+rule + ", " + rule.ordinal());
rules.swapRule(player, other, rule);
getDuel(other).rules.setRules(player, other, rules
.rules);
reset(false);
sendFlash(interfaceId, buttonId);
}
Where it prints Point one, the Rule and its .ordinal is correct, in this case OBSTACLES, 20
But where it passes the rule paramters in rules.swapRule, it changes the ordinal to -1?
public boolean swapRule(Player player, Player other, Rules rule) {
System.out.println("Point 2(swapRule): " + rule + ", " + rule.ordinal());
}
What is causing the Rule parameters to be changes when getting passed as an argument?
Your approah defeats the sheer purpose of using an enumerator. Instead of mangling with indices you could use the Enum directly like this
button.setActionCommand (Rules.HAT.toString ());
Then in your ActoinListener you can determine which button was clicked by using this
public void actionPerformed (ActionEvent e) {
if (Rule.valueOf (e.getActionCommand()) == Rules.HAT) {
//HAT related button was called, process it
}
}
You can get this result by reflection:
import java.lang.reflect.Field;
public class Main {
enum Fruit { APPLE }
public static void main(String[] args) {
try {
Field field = Fruit.class.getSuperclass().getDeclaredField("ordinal");
field.setAccessible(true);
field.set(Fruit.APPLE, -1);
} catch (Exception e) {
}
System.out.println(Fruit.APPLE + ", " + Fruit.APPLE.ordinal());
}
}
However I doubt anyone could do this by mistake.
I'm new to OO programing and having a bit of trouble with the design of my program to use the concepts. I have done the tutorials but am still having problem.
I have a recursion that takes a value of items(could be anything in this example, stocks) and figures out what number of them are needed to equal a specific value(in this code 100). This part works but I want to know if a stock's weighting exceeds a threshold. Originally I approached this problem with a method that did a for loop and calculated the entire list of values but this is super inefficient because its doing it on every loop of the recursion. I thought this would be a good time to try to learn classes because I could use a class to maintain state information and just increment the value on each loop and it'll let me know when the threshold is hit.
I think I have the code but I don't fully understand how to design this problem with classes. So far it runs the loop each step of the recursion because I'm initially the class there. Is there a better way to design this? My end goal is to be notified when a weighting is exceeded(which I can somewhat already do) but I want to do in way that uses the least bit of resources(avoiding inefficient/unnecessary for loops)
Code(Here's the entire code I have been using to learn but the problem is with the Counter class and its location within the findVariables method):
import java.util.Arrays;
public class LearningClassCounting {
public static int[] stock_price = new int[]{ 20,5,20};
public static int target = 100;
public static void main(String[] args) {
// takes items from the first list
findVariables(stock_price, 100, new int[] {0,0,0}, 0, 0);
}
public static void findVariables(int[] constants, int sum,
int[] variables, int n, int result) {
Counter Checker = new Counter(stock_price, variables);
if (n == constants.length) {
if (result == sum) {
System.out.println(Arrays.toString(variables));
}
} else if (result <= sum){ //keep going
for (int i = 0; i <= 100; i++) {
variables[n] = i;
Checker.check_total_percent(n, i);
findVariables(constants, sum, variables, n+1, result+constants[n]*i);
}
}
}
}
class Counter {
private int[] stock_price;
private int[] variables;
private int value_so_far;
public Counter(int[] stock_price, int[] variables) {
this.stock_price = stock_price;
this.variables = variables;
for (int location = 0; location < variables.length; location++) {
//System.out.println(variables[location] + " * " + stock_price[location] + " = " + (variables[location] * stock_price[location]) );
value_so_far = value_so_far + (variables[location] * stock_price[location]);
}
//System.out.println("Total value so far is " + value_so_far);
//System.out.println("************");
}
public void check_total_percent(int current_location, int percent) {
// Check to see if weight exceeds threshold
//System.out.println("we are at " + current_location + " and " + percent + " and " + Arrays.toString(variables));
//System.out.println("value is " + stock_price[current_location] * percent);
//formula I think I need to use is:
if (percent == 0) {
return;
}
int current_value = (stock_price[current_location] * percent);
int overall_percent = current_value/(value_so_far + current_value);
if (overall_percent > 50 ) {
System.out.println("item " + current_location + " is over 50%" );
}
}
}
What you're describing sounds like a variant of the famous knapsack problem. There are many approaches to these problems, which are inherently difficult to calculate.
Inherently, one may need to check "all the combinations". The so-called optimization comes from backtracking when a certain selection subset is already too large (e.g., if 10 given stocks are over my sum, no need to explore other combinations). In addition, one can cache certain subsets (e.g., if I know that X Y and Z amount to some value V, I can reuse that value). You'll see a lot of discussion of how to approach these sort of problems and how to design solutions.
That being said, my view is that while algorithmic problems of this sort may be important for learning how to program and structure code and data structures, they're generally a very poor choice for learning object-oriented design and modelling.