The errors I am getting are "answer cannot be resolved". 1/4th of the way down the page. Looked online still don't see what it should be. Would it be easier to use the while loop instead? skipping the do loop completely?
import java.util.Scanner;
public class RPSS{
//Main method
public static void main(String[ ] argc)
{
Scanner tnt = new Scanner(System.in);
String computerHand; // string variable for computer choice
String userHand; // string variable for user choice
// do loop begining
do
{
computerHand = computerHand();
userHand = userHand();
String winner = getWinner(computerHand, userHand);
System.out.println(winner);
System.out.print("User picks" + userHand );
System.out.println("Computer picks " + computerHand );
System.out.println("play again?");
String answer = tnt.next();
//Condition for the do-while loop HERE IS THE ERROR LOCATION
}while (!answer.Equals("No") && (!answer.Equals("no"))); //condition for while loop
String answer = tnt.next();
}
public static String userHand(){ //method for users choice in the game
//prints message to user giving them choices
System.out.println("Lets play rock paper scissors");
System.out.println("1. Rock ");
System.out.println("2. Paper ");
System.out.println("3. Scissors ");
int userChoice; // user choice variable in this method
Scanner tnt = new Scanner(System.in); // creates instance of scanner class
userChoice = tnt.nextInt(); //reads user input
return getChoice(userChoice); //returns user choice to master choice
}
public static String computerHand() //method for computer generated choice
{
int computernum = (int)(Math.random() * (( 3) + 1));
return getChoice(computernum);
}
public static String getChoice(int num) //method recieving both computer hand and user hand
{
// if statements to place the correct choice
String choice = "";
if (num == 1){
choice = "rock";
}
else if(num == 2){
choice = "paper";
}
else if(num == 3){
choice = "scissors";
}
return choice;
}
// Method determing the winner
public static String getWinner(String computerChoice, String userChoice)
{
computerChoice = computerHand(); //places computerChoice variable in computerhand
userChoice = userHand(); //does same for user choice
String winner="";
System.out.println( " the comp chose" + computerChoice);
if (userChoice.equals("Rock") && computerChoice.equals("Paper")){
System.out.println("The computer"); }
else if (userChoice.equals("Paper") && computerChoice.equals("Scissors")){
System.out.println(" The computer wins");
}
else if (userChoice.equals("Scissors") && computerChoice.equals("Rock")){
System.out.println(" The computer wins ");
}
else if (userChoice.equals("Rock") && computerChoice.equals("Paper")){
System.out.println(" The computer wins ");
}
if (userChoice.equals(computerChoice))
{
System.out.println(" There is no winner");
}
return winner;
}
}
Use tnt.next() which returns the next string. there is no such thing as nextString().
Also, add return winner; at the end of getwinner method.
You declared answer inside the braces of your do and then tried to use it outside the braces. Once you left the braces, the variable was out of scope.
Related
I'm trying to start the game over if the user enters "Yes". I tried using a while loop, but it's gone wrong somewhere that I can't find.
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors {
public static void main(String[] args) {
int playerScore = 0;
int computerScore = 0;
int round = 0;
String decision;
// Get user input
while (round<3) {
System.out.println("Please enter your move: Rock, Paper or Scissors");
System.out.println(">>");
Scanner input = new Scanner(System.in);
String playerMove = input.next();
// Check if user input is valid
if (!playerMove.equalsIgnoreCase("Rock") && !playerMove.equalsIgnoreCase("Paper") && !playerMove.equalsIgnoreCase("Scissors")) {
System.out.println("Move is invalid, Opponent gets a point");
computerScore++;
round++;
System.out.println("Your point is "+ playerScore + "; Opponent score is "+ computerScore);
} else {
// Randomly generate computerMove
int computerInt = (int)(Math.random()*3);
String computerMove = " ";
if (computerInt == 0) {
computerMove = "Rock";
} else if (computerInt == 1) {
computerMove = "Paper";
} else if (computerInt == 2) {
computerMove = "Scissors";}
System.out.println("Opponent move is "+ computerMove);
// Establish winning or losing scenarios
if (playerMove.equalsIgnoreCase(computerMove)) {
System.out.println("Tied");
round++;
System.out.println("Your point is "+ playerScore + "; Opponent score is "+ computerScore);
} else if (playerMove.equalsIgnoreCase("Rock") && computerMove.equalsIgnoreCase("Scissors") ||
playerMove.equalsIgnoreCase("Scissors") && computerMove.equalsIgnoreCase("Paper") ||
playerMove.equalsIgnoreCase("Rock") && computerMove.equalsIgnoreCase("Paper")) {
System.out.println("You won");
playerScore++;
round++;
System.out.println("Your point is "+ playerScore + "; Opponent score is "+ computerScore);
}
else {
System.out.println("You lost");
computerScore++;
round++;
System.out.println("Your point is "+ playerScore + "; Opponent score is "+ computerScore);
}
}
// Determine the last winner
if (playerScore < computerScore) {
System.out.println("You lose, so sad ;(");
} else if (playerScore > computerScore) {
System.out.println("You win, here's a cookie ;) ");
} else {
System.out.println("Tied, maybe try harder ^_^"); }
}
System.out.println("Do you wanna play again?");
}
}
}
Sounds like this might be a HW or Test question, so just writing steps to help you out:
first have a user-decision variable and initialize it to "Y"
then put the game in a while(user-decision="Y") loop
at the end of this loop ask the user for their decision and update the user-decision variable to either Y or N
if they say Y loop continues, else it ends
if you need to repeat your code, put it in a new class (Game) and instantiate in main () and call until your Game class returns TRUE (press Y)
package appMain;
import java.util.Scanner;
public class Game {
public Boolean PlayGame() {
System.out.println("START GAME");
//
// >> PUT THERE YOUT GAME CODE <<
//
Scanner input = new Scanner(System.in);
String answer = input.next();
if(answer.equals("Y")) {
return true;
}
return false;
}
}
package appMain;
public class GameMain {
public static void main(String args[]) {
Game game = new Game();
while (game.PlayGame()) {
}
System.out.println("GAME finish");
}
}
I am new to JAVA and wrote a Nim game project, which includes Nimsys and Nimplayer.
Everything seems fine. When I run through the test file, the result is CORRECT.
However, when it goes to playing again, there's an extra space suddenly shows up, and I cannot
figure it out. There could be some mistakes. Any help is highly appreciated.
The test results
import java.util.Scanner;
public class Nimsys {
int stoneBalance;
public static void main(String[] args) {
String playOrNot;
Scanner input = new Scanner(System.in);// Scanner
System.out.println("Welcome to Nim\n");
// bring two players in the main.
System.out.println("Please enter Player 1's name:");
NimPlayer player1 = new NimPlayer(); // bring player1 object to be used
String name1 = input.nextLine(); // set the string's name to be used
System.out.println("");
NimPlayer player2 = new NimPlayer(); // bring player2 object to be used
System.out.println("Please enter Player 2's name:");
String name2 = input.nextLine();
System.out.println("");
do {
// stone upper bound
System.out.println("Please enter upper bound of stone removal:");
int removeUpBound = input.nextInt();
System.out.println("");
// intital stone numbers
System.out.println("Please enter initial number of stones:");
int totalStone = input.nextInt();
System.out.println("");
NimPlayer numStone = new NimPlayer(); // bring new object to be used
numStone.initialStone(totalStone);
System.out.print(numStone.stoneBalance + " stones left:");
numStone.printStar(totalStone);
// while stoneBalance > 0, two players keep playing the game
while (numStone.stoneBalance > 0) {
// player1's turn and remove the stones; decision of winning
player1.enterName(name1); // pass the name to be used
player1.player1Turn();
int takeStone = input.nextInt();
while (takeStone > removeUpBound || takeStone <= 0) {
System.out.println(
"Invalid, you need to remove stones under upper bound limit or above 0. \n Please enter again.");
takeStone = input.nextInt();
}
numStone.removeStones(takeStone);
if (numStone.stoneBalance > 0) {
System.out.print(numStone.stoneBalance + " stones left:");
numStone.printStar(numStone.stoneBalance);
} else if (numStone.stoneBalance <= 0) {
System.out.println("Game Over\n" + name2 + " wins!\n");
break;
}
// player2's turn and remove the stones; decision of winning
player2.enterName(name2); // pass the name to be used
player2.player2Turn();
int takeStone2 = input.nextInt();
while (takeStone2 > removeUpBound || takeStone2 <= 0) {
System.out.println(
"Invalid, you need to remove stones under upper bound limit or above 0. \n Please enter again.");
takeStone2 = input.nextInt();
}
numStone.removeStones(takeStone2);
if (numStone.stoneBalance > 0) {
System.out.print(numStone.stoneBalance + " stones left:");
numStone.printStar(numStone.stoneBalance);
} else if (numStone.stoneBalance <= 0) {
System.out.println("Game Over\n" + name1 + " wins!\n");
break;
}
}
System.out.println("Do you want to play again (Y/N):");
playOrNot = input.next();
} while (playOrNot.equals("Y"));
}
}
public class NimPlayer {
String player1;
String player2;
int stoneBalance;
int stars;
public void enterName(String name) {
player1 = name;
player2 = name;
}
public void initialStone(int startStones) {
stoneBalance = startStones;
}
public void removeStones(int stonesTaken) {
int updatedBalance = stoneBalance - stonesTaken;
stoneBalance = updatedBalance;
}
public void player1Turn() {
System.out.println(player1 + "'s turn - remove how many?\n");
}
public void player2Turn() {
System.out.println(player2 + "'s turn - remove how many?\n");
}
public void printStar(int star) {
stars = star;
stars = stoneBalance;
for (int stars = 1; stars <= star; stars++) {
System.out.print(" *");
}
System.out.println();
}
}
To entirely fix your 2 issues I would do the following -
input.nextLine();
System.out.println("Do you want to play again (Y/N):");
playOrNot = input.nextLine();
Instead of
System.out.println("Do you want to play again (Y/N):");
playOrNot = input.next();
Alright, I have a class assignment to create 3 predetermined methods for a rock, paper, scissors program written by the teacher. However, when I run the program it running the methods multiple times in a row. I've looked through the code several times and can't figure out the problem.
Below is the teacher provided portion of the program:
public class Game
{
public static void main (String[] args)
{
Scanner in = new Scanner (System.in);
RockPaperScissors rps = new RockPaperScissors (); //***Your class
int numGames = 0;
String userChoice = "";
String cpuChoice = "";
String winner = "";
int userWins = 0;
int cpuWins = 0;
System.out.println("Welcome to Rock, Paper, Scissors!\n");
//Get odd number of games
System.out.println("How many rounds would you like to play?");
numGames = in.nextInt();
while (numGames % 2 == 0) //Even number
{
System.out.println("Sorry, number of games must be odd. Please try again:");
numGames = in.nextInt();
}
//Flush the buffer
in.nextLine();
//Play the game for the number of rounds the user entered
for (int i = 1; i <= numGames; i++)
{
//Get the user and computer choices
userChoice = rps.getUserChoice(); //***Your method
cpuChoice = rps.getCPUChoice(); //***Your method
System.out.println("Computer chooses " + cpuChoice);
//Pick winner
winner = rps.pickWinner(userChoice, cpuChoice); //***Your method
if (winner.equalsIgnoreCase("Tie"))
{
System.out.println("It's a tie! Play again.");
numGames++;
}
else
{
if (winner.equalsIgnoreCase("User"))
{
userWins++;
}
else if (winner.equalsIgnoreCase("Computer"))
{
cpuWins++;
}
else
{
System.out.println("Error in picking winner");
}
System.out.println(winner + " wins!");
}
} //end for
//Print results
System.out.println("\nUser wins: " + userWins);
System.out.println("Computer wins: " + cpuWins);
if (userWins > cpuWins)
{
System.out.println("\nThe user won!");
}
if (cpuWins > userWins)
{
System.out.println("The computer won!");
}
//Close game
System.out.println("\nThank you for playing!");
} //end main
} //end class
And here is my code which I'm assuming where the problem is coming from:
public class RockPaperScissors {
public String getUserChoice() {
Scanner sc = new Scanner (System.in);
System.out.println("Enter your choice:");
String userInput = sc.nextLine();
boolean end = true;
while (end == true){
//Checks for valid user responses
if (userInput.equals("rock") || userInput.equals("paper")|| userInput.equals("scissors")){
end = false;
}
else {
System.out.println("Invalid response. Please enter rock paper or scissors:");
userInput = sc.next();
}
}
return userInput;
}// end getUsechoice
public String getCPUChoice() {
String computerChoice = " ";
Random rand = new Random();
int randomNum = rand.nextInt(3) + 1;
if (randomNum == 1){
computerChoice = "rock";
}
else if (randomNum == 2){
computerChoice = "paper";
}
else if (randomNum == 3){
computerChoice = "scissors";
}
return computerChoice;
}
public String pickWinner(String userChoice, String cpuChoice) {
String result = " ";
if (getUserChoice().equalsIgnoreCase("rock")) {
if (getCPUChoice().equalsIgnoreCase("rock")){
result = "tie";
}
else if (getCPUChoice().equalsIgnoreCase("paper")){
result = "Computer";
}
else if (getCPUChoice().equalsIgnoreCase("scissors")){
result = "User";
}
}
else if (getUserChoice().equalsIgnoreCase("paper")){
if (getCPUChoice().equalsIgnoreCase("paper")){
result = "tie";
}
else if (getCPUChoice().equalsIgnoreCase("rock")){
result = "User";
}
else if (getCPUChoice().equalsIgnoreCase("scissors")){
result = "Computer";
}
}
else if (getUserChoice().equalsIgnoreCase("Scissors")){
if (getCPUChoice().equalsIgnoreCase("scissors")){
result = "tie";
}
else if (getCPUChoice().equalsIgnoreCase("rock")){
result = "Computer";
}
else if (getCPUChoice().equalsIgnoreCase("Paper")){
result = "User";
}
}
return result;
}//end pickWinner
}//end rockPaperScissors
Here would be a sample session of the program:
Welcome to Rock, Paper, Scissors!
How many rounds would you like to play? 1 Enter your choice: rock
Computer chooses paper Enter your choice: rock Enter your choice: rock
Computer wins!
User wins: 0 Computer wins: 1 The computer won!
Thank you for playing!
Here I'm wondering why it continues asking for user input multiple times. Also it runs the other methods as well which is why the computer won despite picking paper vs rock.
Alright added in the final changes to my program and it's working perfectly now:
public String pickWinner(String userChoice, String cpuChoice) {
String result = " ";
if (userChoice.equalsIgnoreCase("rock")) {
if (cpuChoice.equalsIgnoreCase("rock")){
result = "tie";
}
else if (cpuChoice.equalsIgnoreCase("paper")){
result = "Computer";
}
else if (cpuChoice.equalsIgnoreCase("scissors")){
result = "User";
}
}
else if (userChoice.equalsIgnoreCase("paper")){
if (cpuChoice.equalsIgnoreCase("paper")){
result = "tie";
}
else if (cpuChoice.equalsIgnoreCase("rock")){
result = "User";
}
else if (cpuChoice.equalsIgnoreCase("scissors")){
result = "Computer";
}
}
else if (userChoice.equalsIgnoreCase("Scissors")){
if (cpuChoice.equalsIgnoreCase("scissors")){
result = "tie";
}
else if (cpuChoice.equalsIgnoreCase("rock")){
result = "Computer";
}
else if (cpuChoice.equalsIgnoreCase("Paper")){
result = "User";
}
}
return result;
}//end pickWinner
The problem seems to be that when I called in getCPUChoice or getUserChoice it would rerun the program and then change the final answers.
You calling getUserChoice() in the pickWinner method. It should be the userChoice method parameter you should be checking.
public String pickWinner(String userChoice, String cpuChoice) {
String result = " ";
if (userChoice.equalsIgnoreCase("rock")) {
if (cpuChoice.equalsIgnoreCase("rock")){
result = "tie";
}
else if (cpuChoice.equalsIgnoreCase("paper")){
result = "Computer";
}
else if (cpuChoice.equalsIgnoreCase("scissors")){
result = "User";
}
}
else if (userChoice.equalsIgnoreCase("paper")){
if (cpuChoice.equalsIgnoreCase("paper")){
result = "tie";
}
else if (cpuChoice.equalsIgnoreCase("rock")){
result = "User";
}
else if (cpuChoice.equalsIgnoreCase("scissors")){
result = "Computer";
}
}
else if (userChoice.equalsIgnoreCase("Scissors")){
if (cpuChoice.equalsIgnoreCase("scissors")){
result = "tie";
}
else if (cpuChoice.equalsIgnoreCase("rock")){
result = "Computer";
}
else if (cpuChoice.equalsIgnoreCase("Paper")){
result = "User";
}
}
return result;
You should ask for user input in each loop and not just once.
public class RockPaperScissors {
public String getUserChoice() {
Scanner sc = new Scanner (System.in);
System.out.println("Enter your choice:");
//not here
String userInput;
while (true){
//this is the right place
userInput = sc.nextLine();
//Checks for valid user responses
if (userInput.equals("rock") || userInput.equals("paper")|| userInput.equals("scissors")){
break;
}
else {
System.out.println("Invalid response. Please enter rock paper or scissors:");
}
}
return userInput;
}// end getUsechoice
//...
}//end rockPaperScissors
try changing this in your else part
userInput = sc.next();
to this
userInput = sc.nextLine();
So it will go to next line
So the resulting code ll be
while (end == true){
//Checks for valid user responses
if (userInput.equals("rock") || userInput.equals("paper")|| userInput.equals("scissors")){
end = false;
}
else {
System.out.println("Invalid response. Please enter rock paper or scissors:");
userInput = sc.nextLine();
}
}
Whenever I run it, it seems that the loop to continue playing works, but the game outcome is not outputting correctly whenever the conputerChoose executes the randomGenerator. Please help. I'm new to java, and we are only suppose to use 3 methods - instructions, playGame and computerChoose. We are also suppose to use a user controlled loop to continue working. I can't seem to get this right and I still have to add a loop to count the number of time sthe game has been played, the number of times won and the number of times the computer won.
import java.util.*;
public class PRS {
public static Scanner kbd = new Scanner(System.in);
public static void instructions() {
System.out.println("\nThis is the popular game of paper, rock, scissors. Enter your"
+ "\nchoice by typing the word \"paper\", the word \"rock\" or the word"
+ "\n\"scissors\". The computer will also make a choice from the three"
+ "\noptions. After you have entered your choice, the winner of the"
+ "\ngame will be determined according to the following rules:"
+ "\n\nPaper wraps rock (paper wins)"
+ "\nRock breaks scissors (rock wins)"
+ "\nScissors cuts paper (scissors wins)"
+ "\n\nIf both you and the computer enter the same choice, then the game "
+ "\nis tied.\n");
}
public static int playGame(){
int outcome = 0;
System.out.print("Enter your choice: ");
kbd = new Scanner(System.in);
String player = kbd.nextLine().toLowerCase();
String computerChoice = computerChoose();
System.out.println("\nYou entered: " + player);
System.out.println("Computer Chose: " + computerChoose());
if(player.equals(computerChoose())){
outcome = 3;
}
else if (player.equals("paper") && computerChoice.equals("rock")){
outcome = 1;
}
else if (computerChoice.equals("paper") && player.equals("rock")){
outcome = 2;
}
else if (player.equals("rock") && computerChoice.equals("scissors")){
outcome = 1;
}
else if (computerChoice.equals("rock") && player.equals("scissors")){
outcome = 2;
}
else if (player.equals("scissors") && computerChoice.equals("paper") ){
outcome = 1;
}
else if (computerChoice.equals("scissors") && player.equals("paper")){
outcome = 2;
}
else if (player.equals("rock") && computerChoice.equals("paper") ){
outcome = 2;
}
else if (computerChoice.equals("rock") && player.equals("paper")){
outcome = 1;
}
return outcome;
}
public static String computerChoose(){
/*return "scissors";*/
Random generator = new Random();
String [] answer = new String [3];
answer [0]= "paper";
answer [1] = "rock";
answer [2] = "scissors";
return answer[generator.nextInt(3)];
}
public static void main(String[] args) {
kbd = new Scanner(System.in);
System.out.println("THE GAME OF PAPER, ROCK, SCISSORS:");
System.out.print("\nDo you need instructions (Y or N)? ");
String userPlay = kbd.nextLine();
if (userPlay.equalsIgnoreCase("y")){
instructions();
}
String answer;
do{
int result = playGame();
System.out.println(result);
switch (result){
case 1:
System.out.println("YOU WIN!");
break;
case 2:
System.out.println("Comp WINs!");
break;
case 3:
System.out.println("IT'S A TIE!");
break;
default:
}
System.out.print("\nPlay again ( Y or N)? ");
answer = kbd.nextLine();
}while(answer.equalsIgnoreCase("y"));
}
}
The first thing you need to do is only call computerChoose() once. Every time you are calling this method it is generating a new random number and hence a different answer. You should only call it once inside playGame() and assign it to a local variable.
E.g.
String computerChoice = computerChoose();
Then replace all of your other calls to computerChoose() with this variable name. This way you will display the one value and compare only the one value in your logic.
As for tracking other information such as the number of games, and the number of wins/losses, think about declaring a few more class variables (or local variables in the main method) which you can then assign, increment and read. You can do all this from within your do-while loop in the main method. No need for any additional loops.
In addition to Adam's answer, changing the do-while loop at the end to the following will resolve a few different issues.
String answer;
int winCount=0, lossCount=0, tieCount=0;
do{
int result = playGame();
switch (result){
case 1:
System.out.println("YOU WIN!");
winCount++;
break;
case 2:
System.out.println("Comp WINs!");
lossCount++;
break;
case 3:
System.out.println("IT'S A TIE!");
tieCount++;
break;
default:
}
System.out.print("\nPlay again ( Y or N)? ");
answer = kbd.nextLine();
}while(answer.equalsIgnoreCase("y"));
System.out.printf("Wins: %d, Losses: %d, Total plays: %d%n", winCount, lossCount, winCount+lossCount+tieCount);
You need to update result inside the while loop or else only the first game's results will be accurate.
My program is a game to determine how many legs a certain animal (dog/chicken/fish) has.
Every time I run the program, I get an error message:
"Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at AnimalGame.main(AnimalGame.java:67)".
I can't find the problem. Also, I want the program to end after it says "You win!" or "You lose!", but each time it says one of those outputs, it then says
"I don't know that animal. Do you want to try again? (y/n)"
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char n = 0;
char y = 0;
char gameAnswer = 'n';
do
{
System.out.println("Choose an animal: ");
String text = input.nextLine();
switch (text) {
case "dog":
System.out.println("How many legs does a dog have?");
int dg = input.nextInt();
if(dg == 4)
{
System.out.println("You win!");
}
else
{
System.out.println("You lose!");
}
break;
case "chicken":
System.out.println("How many legs does a chicken have?");
int chkn = input.nextInt();
if(chkn == 2)
{
System.out.println("You win!");
}
else
{
System.out.println("You lose!");
}
break;
case "fish":
System.out.println("How many legs does a fish have?");
int fsh = input.nextInt();
if(fsh == 0)
{
System.out.println("You win!");
}
else
{
System.out.println("You lose!");
}
break;
default:
break;
}
System.out.println("I don't know that animal. Do you want to try again? (y/n)");
gameAnswer = input.nextLine().charAt (0);
}while(gameAnswer == 'y');
}
There were a few problems, main one was that when the user enters the number of legs he presses "enter" which adds a newline character right after the int, but since only the int is being read, the newline is being buffered and used on the next read which messes up everything.
The solution to that is to add a readLine() at the end of each case just before the break.
Another issue was that the line:
System.out.println("I don't know that animal. Do you want to try again? (y/n)");
was always printed regardless if the animal was known or not. For that - an addition of a known boolean parameter fixed the issue:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char gameAnswer = 'y';
do {
System.out.println("Choose an animal: ");
String text = input.nextLine();
boolean known = false;
switch (text) {
case "dog":
System.out.println("How many legs does a dog have?");
int dg = input.nextInt();
if (dg == 4) {
System.out.println("You win!");
} else {
System.out.println("You lose!");
}
known = true;
input.nextLine();
break;
case "chicken":
System.out.println("How many legs does a chicken have?");
int chkn = input.nextInt();
if (chkn == 2) {
System.out.println("You win!");
} else {
System.out.println("You lose!");
}
known = true;
input.nextLine();
break;
case "fish":
System.out.println("How many legs does a fish have?");
int fsh = input.nextInt();
if (fsh == 0) {
System.out.println("You win!");
} else {
System.out.println("You lose!");
}
known = true;
input.nextLine();
break;
default:
break;
}
if (!known) {
System.out.println("I don't know that animal. Do you want to try again? (y/n)");
String tmp = input.nextLine().trim();
if (!tmp.isEmpty()) {
gameAnswer = tmp.charAt(0);
}
}
} while (gameAnswer == 'y');
}
Now that we have the code working, it might be a good idea to do some refactoring. I took a few steps and it could probably be improved even further:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char gameAnswer = 'y';
do {
System.out.println("Choose an animal: ");
String text = input.nextLine();
boolean known = getLegs(input, text);
if (!known) {
System.out.println("I don't know that animal. Do you want to try again? (y/n)");
String tmp = input.nextLine().trim();
if (!tmp.isEmpty()) {
gameAnswer = tmp.charAt(0);
}
}
} while (gameAnswer == 'y');
}
private static boolean getLegs(Scanner input, String animal) {
boolean known = identifyAnimal(animal);
if (known) {
System.out.printf("How many legs does a %s have?\n", animal);
int legs = input.nextInt();
if (checkDog(animal, legs) || checkChicken(animal, legs) || checkFish(animal, legs)) {
System.out.println("You win!");
} else {
System.out.println("You lose!");
}
/*
known = true;
input.nextLine();
*/
return; // since the OP stated in the comments that he wants the code to exit here.
}
return known;
}
private static boolean identifyAnimal(String animal) {
return "dog".equals(animal) || "chicken".equals(animal) || "fish".equals(animal);
}
private static boolean checkDog(String animal, int legs) {
return legs == 4 && "dog".equals(animal);
}
private static boolean checkChicken(String animal, int legs) {
return legs == 2 && "chicken".equals(animal);
}
private static boolean checkFish(String animal, int legs) {
return legs == 0 && "fish".equals(animal);
}