Exception in thread "main" after program runs - java

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);
}

Related

how should i make the code give an error if the values are incorrect

I don't know how, but I must add something that gives a massage that the input was wrong if it's a negative vale or a char
package javaapplication6;
import java.util.Scanner;
public class JavaApplication6 {
public static void main(String[] args) {
System.out.print("type in the age: ");
Scanner scn=new Scanner(System.in);
double age=scn.nextDouble();
System.out.print("select your gender (0: female, 1: male):");
double gender=scn.nextDouble();
System.out.print("entere your bp: ");
double bp=scn.nextDouble();
if(age>45){//old male
if(gender==1){
if(bp<12){
System.out.print("bp is low for old man. ");
}
else if(bp>15){
System.out.print("bp is high for old man.");
}
else if(!(bp<12 || bp>15)){
System.out.print("the bp is normal for an old man. ");
}
else {
System.out.print("the value is incorect, please try again");
}
}
}
if(age>45){//old female
if(gender==0){
if(bp<12){
System.out.print("bp is low for old woman. ");
}
else if(bp>14){
System.out.print("bp is high for old woman.");
}
else if(!(bp<12 || bp>14)){
System.out.print("the bp is normal for an old woman. ");
}
else{
System.out.print("the value is incorect, please try again");
}
}
}
}
}
you can do in this way - If any value will be invalid it will take input again rather then throwing.
public static void main(String[] args) {
boolean wrongAge = false;
boolean wrongGender = false;
boolean wrongBP = false;
Scanner scn = null;
double age = 0;
double gender = 0;
double bp = 0;
do{
try{
scn=new Scanner(System.in);
System.out.print("type in the age: ");
wrongAge = false;
age=scn.nextDouble();
}catch(InputMismatchException ime){
wrongAge = true;
}
}while(wrongAge);
do{
try{
scn=new Scanner(System.in);
System.out.print("select your gender (0: female, 1: male):");
wrongGender = false;
gender=scn.nextDouble();
}catch(InputMismatchException ime){
wrongGender = true;
}
}while(wrongGender);
do{
try{
scn=new Scanner(System.in);
System.out.print("entere your bp: ");
wrongBP = false;
bp=scn.nextDouble();
}catch(InputMismatchException ime){
wrongBP = true;
}
}while(wrongBP);
if(age>0){
if(age>45){//old male
if(gender==1){
if(bp<12){
System.out.print("bp is low for old man. ");
}
else if(bp>15){
System.out.print("bp is high for old man.");
}
else if(!(bp<12 || bp>15)){
System.out.print("the bp is normal for an old man. ");
}
else {
System.out.print("the value is incorect, please try again");
}
}
}
if(age>45){//old female
if(gender==0){
if(bp<12){
System.out.print("bp is low for old woman. ");
}
else if(bp>14){
System.out.print("bp is high for old woman.");
}
else if(!(bp<12 || bp>14)){
System.out.print("the bp is normal for an old woman. ");
}
else{
System.out.print("the value is incorect, please try again");
}
}
}
}else{
System.out.print("Incorect age !!!");
}
}
The easiest way is to throw a RunTimeException at any position of your code, like below.
throw new RuntimeException("your message here.");

OverLoading Methods Var cannot be resolved.

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.

Why is this loop looping the code but not performing the correct actions?

When I click retry on this code, it work's and asks how many times to loop flip a coin but the just prints "Flipping Coin(s)" and does nothing. Anyone know how to fix it? I think the error might be coming from X already being less than numloop but I am not sure how to fix it.
Here is my code:
import java.util.Scanner;
public class coinFlip {
public static void main (String[]args)throws InterruptedException {
Scanner sc = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
int numloop;
int x = 0;
String choice;
Boolean bool = true;
while (bool=true){
System.out.println("How Many Coins Would You Like To Flip?");
numloop = sc.nextInt();
if (numloop == 13 || (numloop == 5 || (numloop == 8 || (numloop == 666)))) {
System.out.println("ILLUMINATI CONFIRMED ??????");
System.out.println();
}
System.out.println("Flipping Coin(s)...");
System.out.println();
while (x<numloop) {
int rng = (int)(Math.random()*10+1);
if (rng <= 5) {
System.out.println("You Flipped Heads");
}
else {
System.out.println("You Flipped Tails");
}
x=x+1;
}
System.out.println();
System.out.println("Would You Like To 'Quit' Or 'Retry'?");
choice = scan.nextLine();
if (choice.equalsIgnoreCase("Quit")) {
System.out.println ("Have A Nice Day");
Thread.sleep(1000);
System.exit(0);
}
if (choice.equalsIgnoreCase("Retry")) {
bool=true;
}
}
}
}
Thank You So Much!
If you move int x=0 from outside of your initial while loop to inside of it you won't have this issue. It will reset every time the user retries.
Scanner sc = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
int numloop;
String choice;
Boolean bool = true;
while (bool=true){
int x = 0;
System.out.println("How Many Coins Would You Like To Flip?");
numloop = sc.nextInt();
if (numloop == 13 || (numloop == 5 || (numloop == 8 || (numloop == 666)))) {
System.out.println("ILLUMINATI CONFIRMED ??????");
System.out.println();
}
System.out.println("Flipping Coin(s)...");
System.out.println();
while (x<numloop) {
int rng = (int)(Math.random()*10+1);
if (rng <= 5) {
System.out.println("You Flipped Heads");
}
else {
System.out.println("You Flipped Tails");
}
x=x+1;
}
System.out.println();
System.out.println("Would You Like To 'Quit' Or 'Retry'?");
choice = scan.nextLine();
if (choice.equalsIgnoreCase("Quit")) {
System.out.println ("Have A Nice Day");
Thread.sleep(1000);
System.exit(0);
}
if (choice.equalsIgnoreCase("Retry")) {
bool=true;
}
}
}

Rock Paper Scissors Game (Menu Method)

So as it says in the title, I am trying to create a RPS Game with a Menu as a Method, the thing is I don't know how to call inputs from that menu at any point.
For a better idea, this is my code:
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors
{
public static void main (String [] args)
{
Scanner keyboard = new Scanner (System.in);
String player1choice, player1Name;
int mainMenu,subMenu;
String again;
player1Name = "";
welcomeBanner ();
mainMenu = getMenu (keyboard);
if (mainMenu == 1)
{
keyboard.nextLine();
player1Name = getAName (keyboard);
for (int i = 0; i < 50; ++i) System.out.println();
main (null);
}
if (mainMenu == 2)
{
System.out.println("Welcome "+player1Name); //add name input
subMenu =getsubMenu (keyboard);
System.out.println("You have chosen: "); //add option chosen
System.out.println("Cpu has got, It's a Tie!");//cpuChoice add
}
if (mainMenu == 3)
{
keyboard.nextLine();
String exitRequest;
System.out.print("Are you sure you want to exit? (Y/N): ");
exitRequest = keyboard.nextLine ();
if (exitRequest.equals("y") || exitRequest.equals("Y"))
{
System.out.println("Good Bye!");
System.exit(0);
}
else if (exitRequest.equals("n") || exitRequest.equals("N"))
{
for (int i = 0; i < 50; ++i) System.out.println();
main(null);
}
}
}
static void welcomeBanner()
{
for (int i = 0; i < 60; i++)
{
System.out.print('*');
}
System.out.println("");
System.out.println("* Welcome To The Rock, Paper, Scissors Game *");
System.out.println("*----------------------------------------------------------*");
System.out.println("* Created by: Jonathan Gutierrez, and I am NoxBot! *");
for (int i = 0; i < 60; i++)
{
System.out.print('*');
}
System.out.println("");
System.out.println("");
}
static int getMenu (Scanner aKeyboard)
{
int playermenuChoice;
System.out.println("1. Enter Player Name");
System.out.println("2. Play a Game");
System.out.println("3. Exit Application");
System.out.println("");
System.out.print("Enter your choice: ");
playermenuChoice = aKeyboard.nextInt();
return playermenuChoice;
}
static int getsubMenu (Scanner aKeyboard)
{
int submenuChoice;
System.out.println("Enter 1 for Rock");
System.out.println("Enter 2 for Paper");
System.out.println("Enter 3 for Scissors");
System.out.println("");
System.out.print("Enter choice: ");
submenuChoice = aKeyboard.nextInt();
return submenuChoice;
}
static String getAName (Scanner aKeyboard)
{
String player1Info;
System.out.print("Enter your name: ");
player1Info = aKeyboard.nextLine ();
return player1Info;
}
static String computerChoice ()
{
String cpuChoice;
cpuChoice = "";
Random randomNumbers = new Random();
int cpu = randomNumbers.nextInt (2) + 1;
switch (cpu)
{
case 1:
cpuChoice = "Rock";
break;
case 2:
cpuChoice = "Paper";
break;
case 3:
cpuChoice = "Scissors";
break;
}
return cpuChoice;
}
So when the player chooses option 1, program asks to enter the name of the player, and i want to use that input at any point (most specifically when mainMenu ==2). How can i do that?
EDIT: this is my new code:
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors
{
public static void main (String [] args)
{
Scanner keyboard = new Scanner (System.in);
String player1choice, player1Name, subMenu;
int mainMenu;
String again;
player1Name = "";
welcomeBanner ();
mainMenu = getMenu (keyboard);
if (mainMenu == 1)
{
keyboard.nextLine();
player1Name = getAName (keyboard);
for (int i = 0; i < 50; ++i) System.out.println();
welcomeBanner ();
mainMenu = getMenu (keyboard);
System.out.println("");
System.out.println("Welcome " + player1Name);
System.out.println("");
}
if (mainMenu == 2)
{
subMenu =enterPlayersChoice (keyboard);
keyboard.nextLine();
String cmpu = computerChoice ();
for(int i = 0; i < 3; i ++)
if (subMenu.equals(cmpu))
System.out.println("It's a tie!");
else if (subMenu.equals("rock"))
if (cmpu.equals("scissors"))
System.out.println("Rock crushes scissors. You win!!");
else if (cmpu.equals("paper"))
System.out.println("Paper eats rock. You lose!!");
else if (subMenu.equals("paper"))
if (cmpu.equals("scissors"))
System.out.println("Scissor cuts paper. You lose!!");
else if (cmpu.equals("rock"))
System.out.println("Paper eats rock. You win!!");
else if (subMenu.equals("scissors"))
if (cmpu.equals("paper"))
System.out.println("Scissor cuts paper. You win!!");
else if (cmpu.equals("rock"))
System.out.println("Rock breaks scissors. You lose!!");
else System.out.println("Invalid user input.");
System.out.println("");
}
if (mainMenu == 3)
{
keyboard.nextLine();
String exitRequest;
System.out.print("Are you sure you want to exit? (Y/N): ");
exitRequest = keyboard.nextLine ();
if (exitRequest.equals("y") || exitRequest.equals("Y"))
{
System.out.println("Good Bye!");
System.exit(0);
}
else if (exitRequest.equals("n") || exitRequest.equals("N"))
{
for (int i = 0; i < 50; ++i) System.out.println();
main(null);
}
}
}
static void welcomeBanner()
{
for (int i = 0; i < 60; i++)
{
System.out.print('*');
}
System.out.println("");
System.out.println("* Welcome To The Rock, Paper, Scissors Game *");
System.out.println("*----------------------------------------------------------*");
System.out.println("* Created by: Jonathan Gutierrez, and I am NoxBot! *");
for (int i = 0; i < 60; i++)
{
System.out.print('*');
}
System.out.println("");
System.out.println("");
}
static int getMenu (Scanner aKeyboard)
{
int playermenuChoice;
System.out.println("1. Enter Player Name");
System.out.println("2. Play a Game");
System.out.println("3. Exit Application");
System.out.println("");
System.out.print("Enter your choice: ");
playermenuChoice = aKeyboard.nextInt();
return playermenuChoice;
}
public static String enterPlayersChoice(Scanner aKeyboard)
{
String input = "";
System.out.print("You have a choice of picking rock, paper, or scissors: ");
input = aKeyboard.nextLine();
String inputLower = input.toLowerCase();
return inputLower;
}
static String getAName (Scanner aKeyboard)
{
String player1Info;
System.out.print("Enter your name: ");
player1Info = aKeyboard.nextLine ();
return player1Info;
}
public static String computerChoice ()
{
String cpuChoice;
cpuChoice = "nothing";
Random randomNumbers = new Random();
int cpu = randomNumbers.nextInt (2) + 1;
switch (cpu)
{
case 1:
cpuChoice = "rock";
break;
case 2:
cpuChoice = "paper";
break;
case 3:
cpuChoice = "scissors";
break;
}
return cpuChoice;
}
}
To finish this i want the game to display a message whether player wins or lose, but it is being skipped (mainMenu ==2) any ideas?
Here's a way of rearranging your existing application in a different manner. Some of the major changes include making all methods non-static except the main method, and creating a RockPaperScissorsNew object for the application's point of entry. I've also added class variables so you don't need to pass your Scanner around as an object to all of your methods.
To answer your original question of how you're able to re-use the input entered by the user, the solution I provided is to retain that information within the class variable.
import java.util.Random;
import java.util.Scanner;
public class RockPaperScissorsNew {
//Class variables
Scanner keyboard;
String player1choice, player1Name; //Name will be stored here.
int mainMenu,subMenu;
public RockPaperScissorsNew()
{
keyboard = new Scanner(System.in);
welcomeBanner(); //Display the welcome banner once.
while(true) //Repeatedly display the main menu.
getChoice(); //Get the user's choice
}
public void getChoice()
{
int choice = -1; //Set choice to fail first.
while (choice > 3 || choice < 0) //Wait until user choice passes.
{
choice = getMenu();
}
if (choice == 1) { //Choose your sub option.
getAName(); // Get the user name.
System.out.println("Your name is " + player1Name); //Saved
}
if (choice == 2)
getsubMenu();
if (choice == 3)
System.exit(0);
}
public void welcomeBanner()
{
for (int i = 0; i < 60; i++)
{
System.out.print('*');
}
System.out.println("");
System.out.println("* Welcome To The Rock, Paper, Scissors Game *");
System.out.println("*----------------------------------------------------------*");
System.out.println("* Created by: Jonathan Gutierrez, and I am NoxBot! *");
for (int i = 0; i < 60; i++)
{
System.out.print('*');
}
System.out.println("");
System.out.println("");
}
public int getMenu ()
{
int playermenuChoice;
System.out.println("1. Enter Player Name");
System.out.println("2. Play a Game");
System.out.println("3. Exit Application");
System.out.println("");
System.out.print("Enter your choice: ");
playermenuChoice = Integer.parseInt(keyboard.nextLine().trim());
return playermenuChoice;
}
public int getsubMenu ()
{
int submenuChoice;
System.out.println("Enter 1 for Rock");
System.out.println("Enter 2 for Paper");
System.out.println("Enter 3 for Scissors");
System.out.println("");
System.out.print("Enter choice: ");
submenuChoice = Integer.parseInt(keyboard.nextLine().trim());
return submenuChoice;
}
//This method has been changed to use the class variable, and no longer
//returns a string.
public void getAName ()
{
//String player1Info;
System.out.print("Enter your name: ");
player1Name = keyboard.nextLine ();
//return player1Info;
}
public String computerChoice ()
{
String cpuChoice;
cpuChoice = "";
Random randomNumbers = new Random();
int cpu = randomNumbers.nextInt (2) + 1;
switch (cpu)
{
case 1:
cpuChoice = "Rock";
break;
case 2:
cpuChoice = "Paper";
break;
case 3:
cpuChoice = "Scissors";
break;
}
return cpuChoice;
}
public static void main(String...args)
{
new RockPaperScissorsNew();
}
}

Hangman, exits the game without getting the user response (loop)

I got a couple issues with my code. I know it is not the best looking design/coding but I don't claim to be a good programmer yet. I have to other classes does their work correctly. Dictionary class which contains a word list and HangmanAnimation class which draws the hangman onto console.
Now, I want my game to ask to player if he/she wants to play again after the game finished. Actually, it does asking if player wants to play again but exits the game before the player can type anything.
I would appreciate any other suggestions aswell. Thanks in advance! You guys really rock! :)
public class HangmanGame {
public static void main(String[] args) {
HangmanUI ui = new HangmanUI();
ui.initialize();
String input = "";
if(ui.newGame(input).equalsIgnoreCase("yes"))
main(null);
}
}
public class HangmanUI {
private final Dictionary d = new Dictionary();
private final HangmanAnimation ha = new HangmanAnimation();
private String wordInProgress = d.getWordInProgress();
Scanner sc = new Scanner(System.in);
private int maxTries = 5;
String word;
public void initialize() {
int easyWords = 1;
int hardWords = 2;
System.out.println("Welcome to Hangman game.");
System.out.println("=========================");
System.out.println("Rules: You need to find the given word in 5 tries.");
System.out.println("You will continue guessing letters until you can either");
System.out.println("solve the word or all five body parts are on the gallows.");
System.out.println("In that case you will lose the game. Try not to enter");
System.out.println("same letter more than once. Those are counts too.");
System.out.println();
System.out.println("Choose your game level or Quit:");
System.out.println("1) Easy");
System.out.println("2) Hard");
System.out.println("3) Quit");
try {
int playersChoice = sc.nextInt();
switch (playersChoice) {
case 1:
d.wordList(easyWords);
break;
case 2:
d.wordList(hardWords);
break;
case 3:
System.out.println("Thank you for your time!");
System.exit(0);
default:
System.out.println("Invalid input. Try again!");
initialize();
}
word = d.pickRandomWord(d.getWordList());
hideWord(word);
while(maxTries > 0) {
if(wordInProgress.contains("-")) {
System.out.println(wordInProgress);
revealLetter(notifyGuess());
} else {
System.out.println("Good work! You found the word.");
}
}
} catch (InputMismatchException e) {
System.out.println("Invalid input. Use only digits!");
}
}
//TODO: Do not count same letter more than once & let player to know.
public char notifyGuess() {
ArrayList<Character> charSet = new ArrayList<>();
System.out.print("Please enter a letter: ");
char c = sc.next().charAt(0);
if(Character.isDigit(c)){
System.out.println("You can't use numbers. Please enter a letter.");
notifyGuess();
} else if(charSet.contains(c)) {
System.out.println("You already used '" + c + "' before.");
notifyGuess();
} else
charSet.add(c);
return c;
}
public void hideWord(String word) {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < word.length(); i++) {
sb.append("-");
}
wordInProgress = sb.toString();
}
public void revealLetter(char c) {
try {
String temp = wordInProgress;
char[] charArray = wordInProgress.toCharArray();
for (int i = 0; i < word.length(); i++) {
if(c == word.charAt(i))
charArray[i] = word.charAt(i);
}
wordInProgress = new String(charArray);
if(temp.equals(wordInProgress)){
maxTries--;
ha.drawHanging(maxTries);
} else {
System.out.println("Good! There is '" + c + "' in the word.");
}
} catch (StringIndexOutOfBoundsException e) {
System.err.println("You have to enter a character!");
}
}
public String newGame(String input) {
System.out.println("Do you want to play again? (yes/no)");
input = sc.nextLine();
return input;
}
}
Try using this:
System.out.println("Do you want to play again? (yes/no)");
input = sc.next(); //<== here is the change
return input;

Categories

Resources