public static void main(String[] args) {
Player Anfallare = new Player("A");
Player Forsvarare = new Player("F");
MotVarandra(Anfallare.getDice(1), Forsvarare.getDice(1));
(...)
}
Run Code Online (Sandbox Code Playgroud)
我的主要功能是什么,现在我做了一个自己的功能,
public static void MotVarandra(int a, int f){
if(f >= a){
Anfallare.armees-=1;
}else{
Forsvarare.armees-=1;
}
}
Run Code Online (Sandbox Code Playgroud)
应该将对象的变量设置为 - = 1 ..但这不起作用,因为函数不知道Anfallare和Forsvarare是一个对象..
在这种情况下我该怎么办?
您需要将Players 定义为类字段,而不是在main方法内.
为了温和地介绍Java,我建议你在这里开始阅读:
http://download.oracle.com/javase/tutorial/java/index.html
此外,这里有很棒的书籍建议:https://stackoverflow.com/questions/75102/best-java-book-you-have-read-so-far.其中一些书很适合开始学习.
这里的例子:
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)