Как закодировать определенную область кода после неправильного ввода пользователем? (Ява)
Я работаю над небольшой игрой Rock Paper Scissors с Java, где условие выигрыша или проигрыша основано на том, выиграет ли компьютер или игрок пять игр. Я не уверен, как заставить программу зацикливаться на входе пользователя, если есть неправильный ввод.
Вот код, где у меня эта проблема
Раздел, который я пытаюсь выполнить, - это часть с "else if (definition.equals(" Y ")) {"
import java.util.*;
public class Rock_Paper_Scissors {
public static void main(String arg[]) {
boolean loopGameStart = true;
while (loopGameStart) {
System.out.println("Welcome to Rock Paper Scissors, a game programmed "
+ "by Daniel Park. Would you like to start? (Y/N)");
Scanner userInput = new Scanner(System.in);
String determination = userInput.next();
if (determination.equals("N")) {
System.out.println("Please, do reconsider...");
loopGameStart = true;
} else if (determination.equals("Y")) {
Random rand = new Random();
int n = rand.nextInt(3) + 1;
// 1 = Rock, 2 = Paper, 3= Scissor
int humanWinCount = humanWinCount();
int computerWinCount = computerWinCount();
System.out.println("Choose 0, 1, or 2 (Rock/Paper/Scissor)");
Scanner userRPS = new Scanner(System.in);
int choiceRPS = userRPS.nextInt();
while ((humanWinCount < 5) && (computerWinCount < 5)) {
if (choiceRPS == 0) {
if (n == 1) {
System.out.println("TIE!!");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
} else if (n == 2) {
System.out.println("LOSS!!");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
computerWinCount = computerWinCount + 1;
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
} else if (n == 3) {
System.out.println("WIN!!");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
humanWinCount = humanWinCount + 1;
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
} else {
System.out.println("I do not understand... Try Again.");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
}
} else if (choiceRPS == 1) {
if (n == 1) {
System.out.println("WIN!!");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
humanWinCount = humanWinCount + 1;
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
} else if (n == 2) {
System.out.println("TIE!!");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
} else if (n == 3) {
System.out.println("LOSS!!");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
computerWinCount = computerWinCount + 1;
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
} else {
System.out.println("I do not understand... Try again.");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
}
} else if (choiceRPS == 2) {
if (n == 1) {
System.out.println("LOSS");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
computerWinCount = computerWinCount + 1;
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
} else if (n == 2) {
System.out.println("WIN!!");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
humanWinCount = humanWinCount + 1;
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
} else if (n == 3) {
System.out.println("TIE!!");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
} else {
System.out.println("I do not understand... Try again.");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
}
}
}
if (humanWinCount == 5) {
System.out.println("Congratulations, you win!!");
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
System.out.println("Would you like to try again? (Y/N)");
Scanner continueOrNot = new Scanner(System.in);
String contOrNot = continueOrNot.next();
if (contOrNot.equals("Y")) {
loopGameStart = true;
} else if (contOrNot.equals("N")) {
System.out.println("Okay, goodbye!!");
loopGameStart = false;
}
}
if (computerWinCount == 5) {
System.out.println("Boohoo, you lost!!");
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
System.out.println("Would you like to try again? (Y/N)");
Scanner continueOrNot = new Scanner(System.in);
String contOrNot = continueOrNot.next();
if (contOrNot.equals("Y")) {
loopGameStart = true;
} else if (contOrNot.equals("N")) {
System.out.println("Okay, goodbye!!");
loopGameStart = false;
}
}
} else {
System.out.println("I do not understand, please try again!");
}
}
}
public static int humanWinCount() {
int x = 0;
return x;
}
public static int computerWinCount() {
int c = 0;
return c;
}
}
Ответы
Ответ 1
Пожалуйста, не пишите все в одной основной функции или повторяйте один и тот же код везде и т.д.
Я полностью перестраиваю ваш код, а также реализовал цикл @Austin. Теперь вы должны работать как вы, который или очень близко. Наслаждайтесь:
import java.util.*;
public class Rock_Paper_Scissors
{
public static void main( String arg[] )
{
Rock_Paper_Scissors game = new Rock_Paper_Scissors();
game.startLogic();
}
private Random rand;
private Scanner inputScanner;
private boolean loopGameStart;
private int humanWinCount;
private int computerWinCount;
public Rock_Paper_Scissors()
{
this.rand = new Random();
this.inputScanner = new Scanner( System.in );
this.loopGameStart = true;
humanWinCount = 0;
computerWinCount = 0;
}
public void startLogic()
{
System.out.print( "Welcome to Rock Paper Scissors, a game programmed by Daniel Park. " );
this.askUntilGetAnAnswer( "N" );
}
private int humanWinCount()
{
int x = 0;
return x;
}
private int computerWinCount()
{
int c = 0;
return c;
}
private void askUntilGetAnAnswer( String determination )
{
while( this.loopGameStart )
{
if( !determination.equals( "Y" ) )
{
System.out.println( "\nWould you like to start? (Y/N)" );
determination = this.inputScanner.next();
}
if( determination.equals( "N" ) )
{
System.out.println( "Please, do reconsider..." );
this.loopGameStart = false;
}
else if( determination.equals( "Y" ) )
{
this.processCoreGameLogic();
}
else
{
System.out.print( "I do not understand, please try again!" );
}
}
}
private void processCoreGameLogic()
{
int choiceRPS;
System.out.println( "Choose 0, 1, or 2 (Rock/Paper/Scissor)" );
// 1 = Rock, 2 = Paper, 3= Scissor
this.humanWinCount = this.humanWinCount();
this.computerWinCount = this.computerWinCount();
while( ( this.humanWinCount < 5 ) && ( this.computerWinCount < 5 ) )
{
try
{
choiceRPS = inputScanner.nextInt();
if( choiceRPS >= 0 && choiceRPS <= 2 )
{
this.playing( choiceRPS );
}
}
catch( InputMismatchException e )
{
System.out.print( "I do not understand, please try again!" );
inputScanner.next();
}
}
this.endGame();
}
private void endGame()
{
String contOrNot = "";
if( this.humanWinCount == 5 )
{
System.out.println( "\nCongratulations, you win!!" );
System.out.println( "Computer: " + this.computerWinCount + " rounds won" );
System.out.println( "You: " + this.humanWinCount + " rounds won" );
System.out.println( "Would you like to try again? (Y/N)" );
contOrNot = this.inputScanner.next();
}
if( this.computerWinCount == 5 )
{
System.out.println( "\nBoohoo, you lost!!" );
System.out.println( "Computer: " + this.computerWinCount + " rounds won" );
System.out.println( "You: " + this.humanWinCount + " rounds won" );
System.out.println( "Would you like to try again? (Y/N)" );
contOrNot = this.inputScanner.next();
}
if( contOrNot.equals( "N" ) )
{
System.out.println( "Okay, goodbye!!" );
this.loopGameStart = false;
}
else
{
askUntilGetAnAnswer( contOrNot );
}
}
private void playing( int choiceRPS )
{
int randomInteger = this.rand.nextInt( 3 ) + 1;
// choiceRPS 0 -> tie 1, loss 2, win 3
// choiceRPS 1 -> win 3, tie 1, loss 2
// choiceRPS 2 -> loss 2, win 3, tie 1
//
switch( choiceRPS*3 + randomInteger )
{
case 1:
case 5:
case 9:
{
show_tie();
break;
}
case 2:
case 6:
case 7:
{
show_loss();
break;
}
case 3:
case 4:
case 8:
{
show_win();
break;
}
default:
{
System.out.println( " I do not understand... Try again." );
System.out.println( " Choose 0, 1, or 2 again (Rock/Paper/Scissor)" );
System.out.println( " Computer: " + this.computerWinCount + " rounds won" );
System.out.println( " You: " + this.humanWinCount + " rounds won" );
}
}
}
private void show_loss()
{
System.out.println( "LOSS" );
System.out.println( "Choose 0, 1, or 2 again (Rock/Paper/Scissor)" );
this.computerWinCount = this.computerWinCount + 1;
System.out.println( "Computer: " + this.computerWinCount + " rounds won" );
System.out.println( "You: " + this.humanWinCount + " rounds won" );
}
private void show_win()
{
System.out.println( "WIN!!" );
System.out.println( "Choose 0, 1, or 2 again (Rock/Paper/Scissor)" );
this.humanWinCount = this.humanWinCount + 1;
System.out.println( "Computer: " + this.computerWinCount + " rounds won" );
System.out.println( "You: " + this.humanWinCount + " rounds won" );
}
private void show_tie()
{
System.out.println( "TIE!!" );
System.out.println( "Choose 0, 1, or 2 again (Rock/Paper/Scissor)" );
System.out.println( "Computer: " + this.computerWinCount + " rounds won" );
System.out.println( "You: " + this.humanWinCount + " rounds won" );
}
}
Ответ 2
Вы можете использовать do, пока
int choiceRPS;
do{
choiceRPS = userRPS.nextInt();
}while(choiceRPS<0||choiceRPS>2);
Ответ 3
Ваша логика выглядит очень сложной. Это может быть легко упрощено, так как игра имеет только 3 результата, другие: tie.
SCISSORS бьет БУМАГУ
БУМАГА бьет ROCK
ROCK бьет SCISSORS
Итак, учитывая входы как 0, 1 и 2, представляющие собой скалу, бумагу и ножницы соответственно:
- Вам нужно отслеживать два числа. Один пользователь вводит выбор
назовем его
userChoice
, а другое - computerChoice
, которое
это компьютерный выбор. Этот computerChoice
должен быть
случайно выбранную цифру от 0 до 2 включительно.
- Теперь начните сравнивать оба числа, чтобы определить победителя и
увеличьте соответствующий счетчик (
humanWinCount
и
computerWinCount
).
- Остановите игру и решите победителя, когда либо пользователь, либо
компьютер выигрывает не менее 5 раундов.
Следовательно, ваш игровой цикл должен выглядеть примерно так:
while(true){
System.out.println();
/*
* If either one wins, break out of the game
* and decide the winner.
*/
if(humanWinCount == 5 || computerWinCount == 5){
break;
}
System.out.println("Choose 0, 1, or 2 (Rock/Paper/Scissor)");
//Read user choice
int userChoice = Integer.parseInt(sc.nextLine());
//Computer will play it turn
int computerChoice = rand.nextInt(3);
//Start comparing player choice vs Computer choice
if(userChoice == computerChoice){
tieCount++;
showTieMessage();
}else if(userChoice == 0 && computerChoice == 1){
//User plays ROCK and computer plays PAPER
computerWinCount++;
showComputerWinMessage();
}else if(userChoice == 0 && computerChoice == 2){
//User plays ROCK and computer plays SCISSORS
humanWinCount++;
showHumanWinMessage();
}else if(userChoice == 1 && computerChoice == 0){
//User plays PAPER and computer plays ROCK
humanWinCount++;
showHumanWinMessage();
}else if(userChoice == 1 && computerChoice == 2){
//User plays PAPER and computer plays SCISSORS
computerWinCount++;
showComputerWinMessage();
}else if(userChoice == 2 && computerChoice == 0){
//User plays SCISSORS and computer plays ROCK
computerWinCount++;
showComputerWinMessage();
}else if(userChoice == 2 && computerChoice == 1){
//User plays SCISSORS and computer plays PAPER
humanWinCount++;
showHumanWinMessage();
}else{
System.out.println("Unrecougnized user input!!");
System.out.println("Please Enter correct values!!");
continue;
}
}
И весь переделанный код должен выглядеть примерно так:
public class RockPepperScissor {
private Random rand;
private int humanWinCount;
private int computerWinCount;
private int tieCount; //Not Required, but still keeping in track.
public RockPepperScissor(){
rand = new Random();
humanWinCount = 0;
computerWinCount = 0;
tieCount = 0;
}
public void startGame(){
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to Rock Paper Scissors, a game programmed by Daniel Park. Would you like to start? (Y/N)");
String userChoice = sc.nextLine();
if(userChoice.equalsIgnoreCase("Y")){
startGameLogic(sc);
}else{
if(userChoice.equalsIgnoreCase("N")){
System.out.println("Do you want to reconsider?? (Y/N)");
String secondChance = sc.nextLine();
if(secondChance.equalsIgnoreCase("Y")){
startGameLogic(sc);
}else{
System.exit(0);
}
}else{
System.out.println("Unable to identify your input!! Stopping the game!!");
System.exit(0);
}
}
sc.close();
}
public void startGameLogic(Scanner sc){
while(true){
System.out.println();
/*
* If either one wins, break out of the game
* and decide the winner.
*/
if(humanWinCount == 5 || computerWinCount == 5){
break;
}
System.out.println("Choose 0, 1, or 2 (Rock/Paper/Scissor)");
//Read user choice
int userChoice = Integer.parseInt(sc.nextLine());
//Computer will play it turn
int computerChoice = rand.nextInt(3);
//Start comparing player choice vs Computer choice
if(userChoice == computerChoice){
tieCount++;
showTieMessage();
}else if(userChoice == 0 && computerChoice == 1){
//User plays ROCK and computer plays PAPER
computerWinCount++;
showComputerWinMessage();
}else if(userChoice == 0 && computerChoice == 2){
//User plays ROCK and computer plays SCISSORS
humanWinCount++;
showHumanWinMessage();
}else if(userChoice == 1 && computerChoice == 0){
//User plays PAPER and computer plays ROCK
humanWinCount++;
showHumanWinMessage();
}else if(userChoice == 1 && computerChoice == 2){
//User plays PAPER and computer plays SCISSORS
computerWinCount++;
showComputerWinMessage();
}else if(userChoice == 2 && computerChoice == 0){
//User plays SCISSORS and computer plays ROCK
computerWinCount++;
showComputerWinMessage();
}else if(userChoice == 2 && computerChoice == 1){
//User plays SCISSORS and computer plays PAPER
humanWinCount++;
showHumanWinMessage();
}else{
System.out.println("Unrecougnized user input!!");
System.out.println("Please Enter correct values!!");
continue;
}
}
}
public void showHumanWinMessage(){
System.out.println("YOU WON!!");
System.out.println("Your wins: " + humanWinCount);
System.out.println("Computer wins: " + computerWinCount);
System.out.println("Ties: " + tieCount);
}
public void showComputerWinMessage(){
System.out.println("YOU LOST!!");
System.out.println("Your wins: " + humanWinCount);
System.out.println("Computer wins: " + computerWinCount);
System.out.println("Ties: " + tieCount);
}
public void showTieMessage(){
System.out.println("Tie!!");
System.out.println("Your wins: " + humanWinCount);
System.out.println("Computer wins: " + computerWinCount);
System.out.println("Ties: " + tieCount);
}
public void decideWinner(){
if(humanWinCount > computerWinCount){
System.out.println();
System.out.println("Yippee!! You won the Game!!");
}else if(computerWinCount > humanWinCount){
System.out.println();
System.out.println("Oops!! You lost the Game!!");
System.out.println("Better Luck Next Time!!");
}
}
public static void main(String[] args) {
RockPepperScissor rps = new RockPepperScissor();
rps.startGame();
rps.decideWinner();
}
}
Надеюсь, это поможет вам в вашей учебной деятельности.
Ответ 4
Итак, это довольно заметно, что код не является модульным и в коде имеются избыточные инструкции. Они все еще могут быть там, поскольку все, что я делал, - это исправить логику и высказать замечания по коду для внесенных изменений -
public class Rock_Paper_Scissors {
public static void main(String arg[]) {
boolean loopGameStart = true;
while (loopGameStart) {
System.out.println(
"Welcome to Rock Paper Scissors, a game programmed by Daniel Park. Would you like to start? (Y/N)");
Scanner userInput = new Scanner(System.in);
String determination = userInput.next();
switch (determination) {
case "N":
System.out.println("Please, do reconsider...");
loopGameStart = true; // you might not want the player to be trapped here, so change it to `false` rather
break;
case "Y":
/** 0 = Rock, 1 = Paper, 2 = Scissor */
int humanWinCount = 0;
int computerWinCount = 0;
System.out.println("Choose 0, 1, or 2 (Rock/Paper/Scissor)");
Scanner userRPS = new Scanner(System.in);
int userChoice = userRPS.nextInt();
while ((humanWinCount < 5) && (computerWinCount < 5)) { // either of them reaches 5
int computerChoice = new Random().nextInt(3); // this is fun, no more static computer choice
if (userChoice == computerChoice) { // break quick if its a tie
System.out.println("TIE!!");
displayStats(computerWinCount, humanWinCount);
askChoice();
} else {
switch (userChoice) { //based on userChoice and computerChoice combination
case 0:
if (computerChoice == 1) {
System.out.println("LOSS!!");
displayStats(computerWinCount++,
humanWinCount); // incrementing the computerCount as well
askChoice();
} else if (computerChoice == 2) {
System.out.println("WIN!!");
displayStats(computerWinCount,
humanWinCount++); // incrementing the humanCount as well
askChoice();
}
break;
case 1:
if (computerChoice == 0) {
System.out.println("WIN!!");
displayStats(computerWinCount, humanWinCount++);
askChoice();
} else if (computerChoice == 2) {
System.out.println("LOSS!!");
displayStats(computerWinCount++, humanWinCount);
askChoice();
}
break;
case 2:
if (computerChoice == 0) {
System.out.println("LOSS");
displayStats(computerWinCount++, humanWinCount);
askChoice();
} else if (computerChoice == 1) {
System.out.println("WIN!!");
displayStats(computerWinCount, humanWinCount++);
askChoice();
}
break;
default:
System.out.println("I do not understand... Try again.");
displayStats(computerWinCount, humanWinCount);
askChoice();
break;
}
}
userChoice = userRPS.nextInt(); //next iteration input only required once
}
if (humanWinCount == 5) {
System.out.println("Congratulations, you win!!");
} else {
System.out.println("Boohoo, you lost!!");
}
displayStats(computerWinCount, humanWinCount);
System.out.println("Would you like to try again? (Y/N)");
Scanner continueOrNot = new Scanner(System.in);
String contOrNot = continueOrNot.next();
if (contOrNot.equals("Y")) {
loopGameStart = true;
} else if (contOrNot.equals("N")) {
System.out.println("Okay, goodbye!!");
loopGameStart = false;
}
break;
default:
System.out.println("I do not understand, please try again!");
break;
}
}
}
private static void askChoice() {
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
}
private static void displayStats(int computerWinCount, int humanWinCount) {
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
}
}
Объяснение кода было бы тем, что я оставил бы на том, чего вы не поймете в нем. Поэтому, пожалуйста, спросите о чем-нибудь, что вы, возможно, захотите узнать о том, почему оно используется.
Ответ 5
Если вам нужно закодировать определенный код с условным поведением, попробуйте использовать рекурсивный параметрический метод и заключите код условных частей каждый в отдельный метод. Эти методы будут вызываться из текущей рекурсии. Затем вызовите первый уровень рекурсии из метода main
.
Псевдо-образец:
public int myRecursiveMethod_RPS (int aVariable)
{
System.out.println("Choose 0, 1, or 2 (Rock/Paper/Scissor)");
...
// your own logic below - this is just sample
if (aVariable == 0)
return myRecursiveMethod_RPS(0);
else if (aVariable >= 0)
return myRecursiveMethod_RPS(aVariable);
else return aVariable;
}
Хорошая статья о рекурсии здесь Рекурсия - Java или
здесь https://howtoprogramwithjava.com/java-recursion/
Ответ 6
Попробуйте использовать цикл do/while. Код запускается до тех пор, пока не будет выполнено какое-либо условие, но, по крайней мере, он будет запущен один раз, даже если это условие не является истинным в начале. Используя ваш первый вход в качестве примера, он будет выглядеть примерно так:
String determination; // I move the variable determination outside so it is in the scope of the while.
do {
System.out.println(
"Welcome to Rock Paper Scissors, a game programmed by Daniel Park. Would you like to start? (Y/N)");
Scanner userInput = new Scanner(System.in);
determination = userInput.next();
} while (determination != "Y" || determination != "N");
//...
Код, по крайней мере, будет запускаться один раз. Если в любое время "определение" равно "N" или "Y", оно будет продолжаться с остальной частью кода.
Вы можете получить дополнительную информацию с этого сайта:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html
Ответ 7
Как я уже редактировал в addons_zz модульную версию вашей программы Perambulation: сканер, который используется для userinput, выдает исключение InputMismatchException, если вы вводите, например. Вызывается метод "a" и nextInt() сканера. Ввод "a" не может быть отнесен к типу типа, так как его символ алфавита. Решение этого могло бы выглядеть (в вашей версии кода):
...
} else if (determination.equals("Y")) {
Random rand = new Random();
int n = rand.nextInt(3) + 1;
// 1 = Rock, 2 = Paper, 3= Scissor
int humanWinCount = humanWinCount();
int computerWinCount = computerWinCount();
Scanner userRPS = new Scanner(System.in);
// loop until choiceRPS is 0, 1 or 2
int choiceRPS = 9;
boolean choiceRPSNotSet = true;
while(choiceRPSNotSet){
System.out.println("Choose 0, 1, or 2 (Rock/Paper/Scissor)");
try
{
choiceRPS = userRPS.nextInt();
if( choiceRPS >= 0 && choiceRPS <= 2 )
{
choiceRPSNotSet = false;
}
}
catch( InputMismatchException e )
{
System.out.println( "I do not understand, please try again!" );
userRPS.next();
}
}
// loop until choiceRPS is 0, 1 or 2
while ((humanWinCount < 5) && (computerWinCount < 5)) {
...
Итак, я добавил еще один цикл while, основанный на условии, что choiceRPS установлен правильно.
if( choiceRPS >= 0 && choiceRPS <= 2 )
{
choiceRPSNotSet = false;
}
Только после этого цикл будет оставлен, что включает в себя catching Exceptions, поскольку эта часть находится в блоке try/catch.
Вызов метода userRPS.next() (или Scanner.next()), если произойдет событие InputMismatchException, очистит входной сигнал от сканера, чтобы можно было прочитать новый вход.
Альтернатива, которую я бы рекомендовал, будет инкапсулировать userinput в свой собственный метод, например:
public static int choose(){
Scanner userRPS = new Scanner(System.in);
// loop until choiceRPS is 0, 1 or 2
int choiceRPS = 9;
boolean choiceRPSNotSet = true;
while(choiceRPSNotSet){
System.out.println("Choose 0, 1, or 2 (Rock/Paper/Scissor)");
try
{
choiceRPS = userRPS.nextInt();
if( choiceRPS >= 0 && choiceRPS <= 2 )
{
choiceRPSNotSet = false;
}
}
catch( InputMismatchException e )
{
System.out.println( "I do not understand, please try again!" );
userRPS.next();
}
}
// loop until choiceRPS is 0, 1 or 2
return choiceRPS;
}
И вызывая этот метод select(), когда это необходимо, например:
...
} else if (determination.equals("Y")) {
Random rand = new Random();
int n = rand.nextInt(3) + 1;
// 1 = Rock, 2 = Paper, 3= Scissor
int humanWinCount = humanWinCount();
int computerWinCount = computerWinCount();
int choiceRPS = choose();
while ((humanWinCount < 5) && (computerWinCount < 5)) {
if (choiceRPS == 0) {
if (n == 1) {
System.out.println("TIE!!");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = choose();
} else if (n == 2) {
System.out.println("LOSS!!");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
computerWinCount = computerWinCount + 1;
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = choose();
...
Надеюсь, это поможет! ^^
Ответ 8
import java.util.*;
public class Rock_Paper_Scissors {
public static void main(String arg[]) {
boolean loopGameStart = true;
while (loopGameStart) {
System.out.println("Welcome to Rock Paper Scissors, a game programmed "
+ "by Daniel Park. Would you like to start? (Y/N)");
Scanner userInput = new Scanner(System.in);
String determination = userInput.next();
//1=THIS CHANGED TO IGNORE CASE N or n Y or y accepted
if (determination.equalsIgnoreCase("N")) {
System.out.println("Please, do reconsider...");
loopGameStart = true;
} else if (determination.equals("Y")) {
Random rand = new Random();
int n = rand.nextInt(3) + 1;
// 1 = Rock, 2 = Paper, 3= Scissor
int humanWinCount = humanWinCount();
int computerWinCount = computerWinCount();
System.out.println("Choose 0, 1, or 2 (Rock/Paper/Scissor)");
Scanner userRPS = new Scanner(System.in);
int choiceRPS = userRPS.nextInt();
while ((humanWinCount < 5) && (computerWinCount < 5)) {
if (choiceRPS == 0) {
if (n == 1) {
System.out.println("TIE!!");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
} else if (n == 2) {
System.out.println("LOSS!!");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
computerWinCount = computerWinCount + 1;
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
} else if (n == 3) {
System.out.println("WIN!!");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
humanWinCount = humanWinCount + 1;
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
} else {
System.out.println("I do not understand... Try Again.");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
}
} else if (choiceRPS == 1) {
if (n == 1) {
System.out.println("WIN!!");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
humanWinCount = humanWinCount + 1;
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
} else if (n == 2) {
System.out.println("TIE!!");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
} else if (n == 3) {
System.out.println("LOSS!!");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
computerWinCount = computerWinCount + 1;
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
} else {
System.out.println("I do not understand... Try again.");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
}
} else if (choiceRPS == 2) {
if (n == 1) {
System.out.println("LOSS");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
computerWinCount = computerWinCount + 1;
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
} else if (n == 2) {
System.out.println("WIN!!");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
humanWinCount = humanWinCount + 1;
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
} else if (n == 3) {
System.out.println("TIE!!");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
} else {
System.out.println("I do not understand... Try again.");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
}
}else{
//###################################THIS IS THE ADDED CODE
System.out.println("INVALID VALUE ENTER AGAIN");
System.out.println("Choose 0, 1, or 2 again (Rock/Paper/Scissor)");
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
choiceRPS = userRPS.nextInt();
}
}
if (humanWinCount == 5) {
System.out.println("Congratulations, you win!!");
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
System.out.println("Would you like to try again? (Y/N)");
Scanner continueOrNot = new Scanner(System.in);
String contOrNot = continueOrNot.next();
if (contOrNot.equals("Y")) {
loopGameStart = true;
} else if (contOrNot.equals("N")) {
System.out.println("Okay, goodbye!!");
loopGameStart = false;
}
}
if (computerWinCount == 5) {
System.out.println("Boohoo, you lost!!");
System.out.println("Computer: " + computerWinCount + " rounds won");
System.out.println("You: " + humanWinCount + " rounds won");
System.out.println("Would you like to try again? (Y/N)");
Scanner continueOrNot = new Scanner(System.in);
String contOrNot = continueOrNot.next();
if (contOrNot.equals("Y")) {
loopGameStart = true;
} else if (contOrNot.equals("N")) {
System.out.println("Okay, goodbye!!");
loopGameStart = false;
}
}
} else {
System.out.println("I do not understand, please try again!");
}
}
}
public static int humanWinCount() {
int x = 0;
return x;
}
public static int computerWinCount() {
int c = 0;
return c;
}
}
Ответ 9
Просто простой цикл выполнит трюк:
Scanner answerScanner = new Scanner(System.in);
do{
char answer = answerScanner.next().charAt(0);
}while(answer != 'Y' && answer != 'N');
// Then do whatever you need to do
if(answer == 'Y'){
// Something
}else{
// Something else
}
Обратите внимание, что вы можете использовать answerScanner.next(). toUpperCase(). charAt (0), если вы хотите разрешить "y" и "n" в качестве ответов.