私は幸運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
あなたが参照することができます:http://stackoverflow.com/questions/4403031/scope-of-static-variable-and-methods-in-java –
良い読書..ありがとう.. – DuckStudyingJava