色婷婷狠狠18禁久久YY,CHINESE性内射高清国产,国产女人18毛片水真多1,国产AV在线观看

java猜拳程序類和對象

李中冰1年前8瀏覽0評論

Java猜拳程序是一種經典的編程練習,同時也是面向對象編程的實踐之一。在Java中,我們可以使用類和對象來實現猜拳游戲的功能。

public class Player {
private String name;
private int score;
public Player(String name) {
this.name = name;
this.score = 0;
}
public String getName() {
return name;
}
public void setScore(int score) {
this.score = score;
}
public int getScore() {
return score;
}
}
public class Game {
private Player player1;
private Player player2;
private String[] options = {"Rock", "Paper", "Scissors"};
public Game(String name1, String name2) {
this.player1 = new Player(name1);
this.player2 = new Player(name2);
}
public void playRound() {
int p1Choice = (int) (Math.random() * 3);
int p2Choice = (int) (Math.random() * 3);
System.out.println(player1.getName() + ": " + options[p1Choice]);
System.out.println(player2.getName() + ": " + options[p2Choice]);
if (p1Choice == p2Choice) {
System.out.println("It's a tie!");
} else if ((p1Choice == 0 && p2Choice == 2) || (p1Choice == 1 && p2Choice == 0) || (p1Choice == 2 && p2Choice == 1)) {
System.out.println(player1.getName() + " wins!");
player1.setScore(player1.getScore() + 1);
} else {
System.out.println(player2.getName() + " wins!");
player2.setScore(player2.getScore() + 1);
}
}
public void playGame(int numRounds) {
for (int i = 0; i< numRounds; i++) {
System.out.println("Round " + (i+1));
playRound();
System.out.println(player1.getName() + ": " + player1.getScore() + " | " + player2.getName() + ": " + player2.getScore() + "\n");
}
System.out.println("Final Score: " + player1.getName() + ": " + player1.getScore() + " | " + player2.getName() + ": " + player2.getScore());
}
}
public class Main {
public static void main(String[] args) {
Game game = new Game("Player 1", "Player 2");
game.playGame(5);
}
}

在上面的代碼中,我們定義了兩個類:Player和Game。Player類表示游戲中的一個玩家,包含名字和分數兩個屬性。Game類表示整個猜拳游戲,包含兩個Player對象和游戲選項(石頭、剪刀、布)數組。其中,playRound()方法表示一局游戲的過程,通過隨機生成玩家的選擇并進行比較得出勝利者。playGame()方法則表示整個游戲的過程,通過調用playRound()方法,并輸出玩家分數以及最終比分。