所以我今天的任務是使用方法做一個石頭紙剪刀遊戲。我的代碼的第一個問題是,我需要它來詢問用戶是否要再次玩。 (y或n)另外,我需要實現得分,如果用戶獲勝,則得1分,如果失敗,則爲-1,並且每次他們再次玩都將該得分添加到總得分。關於如何實現這個的任何想法?或者我需要更改爲我的代碼。另外,我是一個新手,對於醜陋的格式感到抱歉,並隨時批評每一個小細節,因此我不能吸收所有可能的信息。巖紙剪刀簡單的java使用方法
public static void main(String[] args){
boolean tie = true;
do{
String computer = computerChoice();
String user = userChoice();
tie = (computer.compareTo(user) == 0);
determineWinner(computer, user);
}while(tie);
}
public static String computerChoice(){
Random rand = new Random();
int cinput = rand.nextInt(3)+ 1;
String computer = "thing";
if (cinput == 1)
computer = "Rock";
if (cinput == 2)
computer = "Paper";
if (cinput == 3)
computer = "Scissors";
return computer;
}
public static String userChoice(){
Scanner sc = new Scanner (System.in);
String user = "default";
do{
System.out.println("choose your weapon(Paper,Scissors or Rock)");
user = sc.nextLine();
}
while (isValidChoice (user) == false);
return user;
}
public static boolean isValidChoice(String choice){
boolean status;
if (choice.compareTo("Rock")== 0)
status = true;
else if (choice.compareTo("Paper")== 0)
status = true;
else if (choice.compareTo("Scissors")== 0)
status = true;
else{
status = false;
System.out.println("Error! Make sure you are capitalizing your choices");
}
return status;
}
public static boolean determineWinner(String computer, String user){
System.out.println (" Computer Choice: " + computer);
System.out.println ("Your Choice : " + user);
if (computer.compareTo("Rock") == 0 && user.compareTo ("Scissors") == 0)
System.out.println (" Computer wins! Better luck next time!");
if (computer.compareTo("Scissors")== 0 && user.compareTo("Paper") == 0)
System.out.println (" Computer wins! Better luck next time!");
if (computer.compareTo("Paper") == 0 && user.compareTo("Rock") == 0)
System.out.println (" Computer wins! Better luck next time!");
if (computer.compareTo("Rock") == 0 && user.compareTo("Paper") == 0)
System.out.println (" You win!!");
if (computer.compareTo("Scissors") == 0 && user.compareTo("Rock") == 0)
System.out.println (" You win!!");
if (computer.compareTo("Paper") == 0 && user.compareTo("Scissors") == 0)
System.out.println (" You win!!");
else if (computer.compareTo(user) == 0){
System.out.println(" Tie! the game must be played again.");
return false;
}
return true;
}
}
,我的教授給我們作爲一個例子輸出爲:
Choose your weapon!
1. Paper
2. Scissors
3. Rock
5
Choose your weapon!
1. Paper
2. Scissors
3. Rock
1
You chose paper!
I choose rock!
I have been vanquished!
We have matched wits 1 times, and your score is 1
Do you want to play again (y or n)? y
Choose your weapon!
1. Paper
2. Scissors
3. Rock
1
You chose paper!
I choose paper!
We are equally matched. You are a worthy adversary.
We have matched wits 2 times, and your score is 1
Do you want to play again (y or n)? n
你知道怎麼反覆要求一個「武器」,但不知道怎麼反覆要求再玩一次? –
使用.equals()可以更好地檢查響應 – WIR3D
@ScottHunter,所以我只需製作另一種方法並讓它們再次播放? – Progamminnoob