我正在做一个幸运9的简单纸牌游戏,我希望计数器增加所以我可以记录每个玩家的胜利数量,我已经宣布winCount为静态但每次我点击运行程序计数器输出1或0;
import java.util.Random;
public class Tester {
static int p1WinCount;
static int p2WinCount;
public static void main(String[] args) {
Random rand = new Random();
Tester test = new Tester();
String player1 = "PLAYER 1";
int p1r1 = rand.nextInt(13)+1;
int p1s1 = rand.nextInt(4)+1;
int p1r2 = rand.nextInt(13)+1;
int p1s2 = rand.nextInt(4)+1;
int p1total = test.total(test.convRank1(p1r1), test.convRank2(p1r2));
System.out.println(player1);
System.out.printf("Card 1: %s of %s\n", test.getRank(p1r1), test.getSuit(p1s1));
System.out.printf("Card 2: %s of %s\n", test.getRank(p1r2), test.getSuit(p1s2));
System.out.printf("Card Total: %d\n", p1total);
System.out.println();
String player2 = "PLAYER 2";
int p2r1 = rand.nextInt(13)+1;
int p2s1 = rand.nextInt(4)+1;
int p2r2 = rand.nextInt(13)+1;
int p2s2 = rand.nextInt(4)+1;
int p2total = test.total(test.convRank1(p2r1), test.convRank2(p2r2));
System.out.println(player2);
System.out.printf("Card 1: %s of %s\n", test.getRank(p2r1), test.getSuit(p2s1));
System.out.printf("Card 2: %s of %s\n", test.getRank(p2r2), test.getSuit(p2s2));
System.out.printf("Card Total: %d\n", p2total);
System.out.println();
if(p1total > p2total) {
System.out.println("PLAYER 1 IS THE WINNER");
p1WinCount++;
} else {
System.out.println("PLAYER 2 IS THE WINNER");
p2WinCount++;
}
System.out.println();
System.out.printf("Player 1 wins %d times / Player 2 wins %d times", p1WinCount, p2WinCount);
}
public String getRank(int x) {
switch(x) {
case 1:
return "ACE";
case 2:
return "TWO";
case 3:
return "THREE";
case 4:
return "FOUR";
case 5:
return "FIVE";
case 6:
return "SIX";
case 7:
return "SEVEN";
case 8:
return "EIGHT";
case 9:
return "NINE";
case 10:
return "TEN";
case 11:
return "JACK";
case 12:
return "QUEEN";
case 13:
return "KING";
} return null;
}
public String getSuit(int x) {
switch(x) {
case 1:
return "DIAMOND";
case 2:
return "CLUBS";
case 3:
return "HEARTS";
case 4:
return "SPADE";
} return null;
}
public int convRank1(int x) {
if(x > 9) {
return x - 9;
} else {
return x;
}
}
public int convRank2(int x) {
if(x > 9) {
return x - 9;
} else {
return x;
}
}
public int total(int x, int y) {
if(x + y > 9) {
return x + y - 9;
} else {
return x + y;
}
}
}
这是输出:
PLAYER 1
Card 1: FIVE of SPADE
Card 2: QUEEN of SPADE
Card Total: 8
PLAYER 2
Card 1: FOUR of SPADE
Card 2: ACE of CLUBS
Card Total: 5
PLAYER 1 IS THE WINNER
Player 1 wins 1 times / Player 2 wins 0 times
答案 0 :(得分:2)
您需要将计数存储/保存到文件或数据库(磁盘存储器),只需声明静态计数器不会在多次运行中保留数据
静态计数器(实际上所有程序变量)仅在程序执行(运行)期间位于主存储器(RAM)中,并且在程序运行终止后将不可用。因此,当您再次启动程序时,它将是一个全新的运行,您无法获得以前的运行数据。
答案 1 :(得分:0)
程序完成后,静态变量将被清除。您必须让您的程序将每个玩家的获胜次数写入文件,或者在有人获胜后继续运行(添加重启按钮)。静态变量不会持续超过程序的生命周期,它们根本不属于对象。