我是编程的新手,由于某种原因,这个程序不计算分数 - 我的分数总是为0(例如它只打印我们的分数:0他们的分数:0)这是我的程序:
public static void main (String[] args){
Scanner in = new Scanner(System.in);
boolean warmonger=false;
int playerScore=0;
int aiScore=0;
theIntro();
for (int i=0;i<GAMES;i++){
scoreCounter(playerScore, aiScore);
playerInput(in, warmonger, playerScore, aiScore);
}
}
public static void scoreCounter(int playerScore, int aiScore){
System.out.println("=====");
System.out.println("Our score: "+playerScore);
System.out.println("Their score: "+aiScore);
}
public static void playerInput(Scanner in, boolean warmonger, int playerScore, int aiScore){
System.out.print("What is your strategy this year? ");
String strat=in.next();
if (strat.equalsIgnoreCase("peace")){
peaceStrat(warmonger, playerScore, aiScore);
}
else if (strat.equalsIgnoreCase("war")){
warStrat(warmonger, playerScore, aiScore);
}
else {
while (!strat.equalsIgnoreCase("peace") && !strat.equalsIgnoreCase("war")){
System.out.print("Invalid strategy. Enter \"peace\" or \"war\": ");
strat=in.next();
}
}
}
public static void peaceStrat(boolean warmonger, int playerScore, int aiScore){
String aiStrat=getStrategy("peace", warmonger);
if (aiStrat=="peace"){
playerScore+=3;
aiScore+=3;
System.out.println("peace");
}
else if (aiStrat=="war"){
aiScore+=5;
System.out.println("we lost");
}
}
public static void warStrat(boolean warmonger, int playerScore, int aiScore){
warmonger=true;
String aiStrat=getStrategy("war", warmonger);
if (aiStrat=="peace"){
playerScore+=5;
System.out.println("we won");
}
else if (aiStrat=="war"){
playerScore+=1;
aiScore+=1;
System.out.println("tie");
}
}
我是否需要以某种方式返回分数?
答案 0 :(得分:2)
您总是在修改乐谱的本地版本。修改方法中的int
不会修改在中传递给方法的int
。
现在您可以考虑将分数保持为“类变量”,即在方法之外声明的static int
变量。
最终你可能想把它们作为实例变量包装起来;他们所属的地方取决于你最终如何分解申请职责。
答案 1 :(得分:2)
aiStrat=="peace"
这不是你如何比较java中的字符串。它应该是
aiStrat.equals("peace");
您可能没有点击会导致分数更新的代码。
另外,更改
int playerScore=0;
int aiScore=0;
要
static int playerScore = 0;
static int aiScore = 0;
正如Dave Newton指出的那样,你需要将这些变量移到主函数之外。