Reputation: 18103
public static void main(String[] args) {
Player Anfallare = new Player("A");
Player Forsvarare = new Player("F");
MotVarandra(Anfallare.getDice(1), Forsvarare.getDice(1));
(...)
}
Is what I have in main function, now I made a own function,
public static void MotVarandra(int a, int f){
if(f >= a){
Anfallare.armees-=1;
}else{
Forsvarare.armees-=1;
}
}
which should set the object's variable to -=1.. But this doesn't work because the function doesnt know that Anfallare and Forsvarare is an object..
What can i do in this case?
Upvotes: 1
Views: 2292
Reputation: 40391
You need to define the Player
s as class fields, instead of inside the main method.
For a gentle introduction to Java, I suggest you to start reading here:
http://download.oracle.com/javase/tutorial/java/index.html
Also, there are great book suggestions here: https://stackoverflow.com/questions/75102/best-java-book-you-have-read-so-far . Some of those books are great to begin learning.
Example here:
public class Game {
private static Player Anfallare, Forsvarare; // <-- you define them here, so they are available to any method in the class
public static void main(String[] args) {
Anfallare = new Player("A"); // <-- it is already defined as a Player, so now you only need to instantiate it
Forsvarare = new Player("F");
MotVarandra(Anfallare.getDice(1), Forsvarare.getDice(1));
// ...
}
public static void MotVarandra(int a, int f){
if(f >= a){
Anfallare.armees-=1; // <-- it is already defined and instantiated
}else{
Forsvarare.armees-=1;
}
}
}
Upvotes: 5
Reputation: 679
While Aleadam's solution is by far the best answer, another thing you could do to specifically resolve this issue is change the arguments of the function:
public static void MotVarandra(Player a, Player f){
if(f.getDice(1) >= a.getDice(1)){
f.armees-=1;
}else{
a.armees-=1;
}
}
Ultimately, your optimal solution just depends on what your program is doing. Chances are, this is just another way of looking at it.
As a side note, be sure to use descriptive naming techniques, a and f are somewhat hard coded, and only make sense if you use only those variable names for your Players. It's best to not potentially limit your code.
Upvotes: 2