Я создаю игру из камня, бумаги, ножниц, чтобы попробовать свои навыки Java. В моем коде у меня есть цикл while, цикл которого округляется до тех пор, пока победитель не выиграет или не потеряет количество раундов, которые они ввели. Эта часть не работает. Он идет прямо к логическому выражению, которое вне цикла while, хотя оно не завершило этот цикл.
код:
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 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 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();
}
}
Почему он не зацикливается, как предполагается? Я действительно не могу понять это
Проблема заключается в вашем заявлении о нарушении
if (Arrays.asList(choices).contains(yourChoice)) { // what use entered
break;
}
break
заставит вас выйти из цикла, и я не думаю, что вы хотите выйти из цикла, когда вы выбрали правильный ввод.
в действительности, поскольку у вас также есть команда System.exit
внутри блока else
, ни один из ваших внутренних циклов while не будет выполняться после этих двух строк, независимо от того, что.
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);
}
Я бы рекомендовал избавиться от инструкции break
и изменить System.exit(0);
для continue
, который просто перейдет к следующей итерации цикла. Если вы это сделаете, вы также сможете переработать if-логику, поскольку существует только 1 условие.
while (running = true)
должен быть while (running == true)
Изменение: загляните в Условия Йоды как способ избежать этого.
while(running)
. :)
Как и @David Ehrmann, вам нужно изменить ваш running = true
на running == true
или просто while(running)
, ваша логика в этом случае неверна:
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);
}
Вы не хотите break
когда вы ввели правильный ввод. Правильное утверждение должно быть:
if (!(Arrays.asList(choices).contains(yourChoice)))
{
System.out.println("You did not enter either Rock, Paper, or Scissors.");
running = false;
break;
}
else
{
// the rest of the playing code
}
Это предполагает, что вы хотите изящно выйти. Он должен напечатать "Это ничья". и очистить любые ресурсы таким образом... если это то, что вы хотите.
break;
if
после внешнего ...