我正在創建一個岩石,紙張,剪刀遊戲以嘗試我的Java技能。在我的代碼中,我有一個循環循環,直到贏家贏得或輸掉他們輸入的循環數。這部分不起作用。它直接進入邏輯語句,即使沒有完成循環,它也在while循環之外。Java程序不環繞while循環 - 直接轉到if語句
代碼:
package rps_game;
// Rock, Paper, Scissors game
//
import java.util.*;
public class rock_paper_scissors {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
Scanner lineInput = new Scanner(System.in);
Random rand = new Random();
String choices[] = { "rock", "paper", "scissors" };
int winRounds = 0;
boolean running = true;
int rounds = 0;
int wins = 0;
int loses = 0;
String yourChoice = "";
String compChoice = "";
while (running = true) { // main loop
try {
System.out
.println("Enter the amount of rounds you want to play: ");
rounds = input.nextInt(); // gets input
winRounds = (rounds/2) + 1;
System.out.println("You are playing best of " + winRounds
+ " out of " + rounds);
//running = false; // breaks off from loop
while (wins < winRounds && loses < winRounds) { // this while loop
System.out.println("Enter either Rock, Paper or Scissors: ");
yourChoice = lineInput.nextLine();
yourChoice= yourChoice.toLowerCase();
if (Arrays.asList(choices).contains(yourChoice)) { // what use entered
break;
} else {
System.out.println("You did not enter either Rock, Paper or Scissors.");
System.exit(0);
}
compChoice = choices[rand.nextInt(choices.length)];
System.out.println("ROCK.. PAPER.. SCISSORS!");
System.out.println("You entered: " + yourChoice + " and the computer entered: " + compChoice);
if (yourChoice.equals(compChoice)){
System.out.println("\nIt's a draw!");
}else if(yourChoice.equals("rock") && compChoice.equals("paper")){
System.out.println("\nYou lose!");
loses++;
}else if(yourChoice.equals("paper") && compChoice.equals("rock")){
System.out.println("\nYou win!");
wins++;
}else if(yourChoice.equals("scissors") && compChoice.equals("paper")){
System.out.println("\nYou win!");
wins++;
}else if(yourChoice.equals("paper") && compChoice.equals("Scissors")){
System.out.println("\nYou lose!");
loses++;
}else if(yourChoice.equals("rock") && compChoice.equals("scissors")){
System.out.println("\nYou win!");
wins++;
}else if(yourChoice.equals("scissors") && compChoice.equals("rock")){
System.out.println("\nYou lose!");
loses++;
}else{
break;
}
}
System.out.println("\nGAME FINISHED!");
if (wins > loses){
System.out.println("\nYOU WIN THE GAME!!");
}else if(wins < loses){
System.out.println("\nYOU LOST THE GAME!! :(");
}else{
System.out.println("It's a draw!!");
System.exit(0);
}
} catch (Exception e) { // if error pops up
System.out.println("You DID NOT enter a WHOLE NUMBER.");
break;
}
}
input.close();
lineInput.close();
}
}
爲什麼沒有像循環它應該是?我真的不知道這一點
@KubaSpatny是的。打破內在,同時是OP描述的問題 –
是的抱歉,我在我的手機上看着它,並認爲'如果'是在外面以後.. –
是的!非常感謝。在Java和其他語言的while循環方面我還沒有太多的經驗。但是謝謝你! – user3092741