Java word shuffle game [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm having tons of issues with this program. I can't get my string comparisons to work and I have several infinite loops that I'm not sure how to fix. I would appreciate a fresh set of eyes to show me what I'm missing, I've been staring at this for 3 days and I keep skipping over my errors. The program needs to pick a random word from the given text file, scramble up that word, then have the user guess what the original word was. Hints should display what letter is at a given random position within the word.
import java.util.Scanner;
import java.util.Random;
import java.io.*;
import java.util.*;
public class Proj4 {
public static void main (String[] args) throws IOException{
int wordScore = 10;
int score = 0;
boolean game = true;
int i = 0;
Scanner in = new Scanner(System.in);
char responseLetter = 'n';
boolean allTrue = false;
boolean scramble = true;
StringBuilder sb = new StringBuilder ();
int counter = 0;
int position = 0;
System.out.println("Enter in a file containing words (Ex: words.txt) : ");
String filename = in.nextLine();
Scanner inFile = new Scanner(new File(filename));
String size = inFile.nextLine();
System.out.println(size);
int arrayLength = Integer.parseInt(size);
String[] wordList = new String[arrayLength];
Random rndm = new Random();
while (inFile.hasNext()) {
// this section puts the contents of the text file into the array
wordList[i] = inFile.nextLine();
i++;
}
while (game == true) {
// System.out.println("Current puzzle: " + scrambledWord);
// System.out.println("Current points for word " + wordScore);
// System.out.println("Enter (g)uess, (n)ew word, (h)int, or (q)uit: ");
// responseLetter = in.next().charAt(0);
if (responseLetter == 'n') {
// goes back to the beginning but does not change word. I cant move the picker down becauase it throws off g
String pickedWord = wordList[rndm.nextInt(arrayLength )];
boolean [] used = new boolean[pickedWord.length()] ; // the random word gets picked here
String [] letters = pickedWord.split("");
while (allTrue == false) {
int randomLetter = rndm.nextInt(pickedWord.length());
if (used[randomLetter] != true) {
sb.append(letters[randomLetter].charAt(0)); // does this line work?
used[randomLetter] = true;
} else if (used[randomLetter]== true) {
scramble = true;
counter++;
}
if (counter > (2 * pickedWord.length())) {
allTrue = true;
}
}
String scrambledWord = sb.toString();
if (scrambledWord.equals(pickedWord)) {
System.out.println("The words match");
allTrue = false;
}
System.out.println("Current puzzle: " + scrambledWord);
System.out.println("Current points for word " + wordScore);
System.out.println("Enter (g)uess, (n)ew word, (h)int, or (q)uit: ");
responseLetter = in.next().charAt(0);
} else if (responseLetter == 'g') {
// automatically says guess is wrong. something wrong with equals()?
System.out.println("Enter your guess: ");
in.nextLine();
String guess = in.nextLine();
if (guess.equals(pickedWord)) {
System.out.println("You guessed it!");
score += wordScore;
game = true;
} else if (!guess.equals(pickedWord)) {
System.out.println("Oops! Try again.");
wordScore--;
System.out.println("Current points for word " + wordScore);
System.out.println("Enter (g)uess, (n)ew word, (h)int, or (q)uit: ");
responseLetter = in.next().charAt(0);
}
} else if (responseLetter == 'h') {
//THIS BLOCK WORKS. DONT EVEN LOOK AT IT
Random r = new Random();
int hint = r.nextInt(pickedWord.length());
System.out.println(hint);
char letterAtSpot = pickedWord.charAt(hint);
System.out.println("The letter at spot " + hint + " is " + letterAtSpot);
wordScore--;
} else if (responseLetter == 'q') {
game = false;
} else {
System.out.println("Invalid Choice - 'g', 'n', 'h', 'q' only.");
responseLetter = 'n';
}
}
System.out.println("Goodbye!");
System.out.println("Total score: " + score);
}
}

Right out of the gate, I had a compilation error because pickedWord is being referenced outisde of the if statement in which it was declared. So, by the time it got to if (guess.equals(pickedWord)), the compiler doesn't know what pickedWord is.

The first thing that popped out at me was the if/else ladder.
String scrambledWord = sb.toString();
if (scrambledWord.equals(pickedWord)) {
System.out.println("The words match");
allTrue = false;
}
System.out.println("Current puzzle: " + scrambledWord);
System.out.println("Current points for word " + wordScore);
System.out.println("Enter (g)uess, (n)ew word, (h)int, or (q)uit: ");
responseLetter = in.next().charAt(0);
}
Notice how you close your if statement before getting a response for responseLetter. This means, your loop condition: "while game == true" isn't properly being evaluated.

Related

Trying to iterate certain interval using "do -while"

Hi this code is part of my code that is supposed to check if the number string is palindrome.
I want to iterate from top to botoom of my code but it doesn't iterate at all , what is wrong ??
I searched in youtube and realized this kind of things , people usually use do-while loop so I was trying to follow the instruction but it doesn't give me what I want .
do {
System.out.println("You passed Catch-Block stage! , Please enter the number that you want to check if it is palindrome");
String str = kbd.nextLine().trim();
String org_str = str;
String rev = "";
int len = str.length();
for (int i = len - 1; i >= 0; i--) {
rev = rev + str.charAt(i);
}
if (org_str.equals(rev)) {
System.out.println(org_str + " is Palindrome Number");
} else {
System.out.println(org_str + "is Not Palindrome String");
}
System.out.println("Do you want to continue Y or N");
choice = kbd.next().charAt(0);
}while(choice=='y'||choice =='Y');
}
Here is my full code.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
char choice;
long firstNum = 0;
firstNum = getLong(" Enter the first number: ", '-');
do {
System.out.println("You passed Catch-Block stage! , Please enter the number that you want to check if it is palindrome");
String str = kbd.nextLine().trim();
String org_str = str;
String rev = "";
int len = str.length();
for (int i = len - 1; i >= 0; i--) {
rev = rev + str.charAt(i);
}
if (org_str.equals(rev)) {
System.out.println(org_str + " is Palindrome Number");
} else {
System.out.println(org_str + "is Not Palindrome String");
}
System.out.println("Do you want to continue Y or N");
choice = kbd.next().charAt(0);
}while(choice=='y'||choice =='Y');
}
public static long getLong(String prompt, char exitChar)
{
long retVal = 0;
boolean validInput = false;
String userInput = "";
Scanner kbd = new Scanner(System.in);
while (!validInput) {
System.out.println(prompt);
try
{
userInput = kbd.nextLine().trim();
if (userInput.length() > 0 && userInput.charAt(0) == exitChar)
{
System.out.println("Ending the program at the user's request");
System.exit(1);
}
retVal = Long.parseLong(userInput);
validInput = true;
}
catch (Exception ex)
{
System.out.println("That is not numeric. Try again or press " + exitChar + "to Quit");
}
}
return retVal;
}
}
Change this:
String str = kbd.nextLine().trim();
to this
String str = kbd.next();
When read choice, using nextLine() intead of next():
do {
System.out.println("You passed Catch-Block stage! , Please enter the number that you want to check if it is palindrome");
String str = kbd.nextLine().trim();
String org_str = str;
String rev = "";
int len = str.length();
for (int i = len - 1; i >= 0; i--) {
rev = rev + str.charAt(i);
}
if (org_str.equals(rev)) {
System.out.println(org_str + " is Palindrome Number");
} else {
System.out.println(org_str + "is Not Palindrome String");
}
System.out.println("Do you want to continue Y or N");
choice = kbd.nextLine().charAt(0); // <---here, change to nextLine()
}while(choice=='y'||choice =='Y');
}
next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input. so in next loop it reads last input line that will be empty string.

Hangman stats error

My code does not show the number of wins, losses and numberOfGames I had played.
I've been trying to fix it for the last month and I'm going nowhere!
import java.util.Random;
import java.util.Scanner;
public class HangmanP2 {
public static void main(String[] args) {
Scanner Input = new Scanner(System.in);
String first, reverse = "";
String second, reverse2 = "";
Scanner in = new Scanner(System.in);
System.out.println("Welcome to Hangman!");
System.out.println("Enter your first name.");
first = in.nextLine();
System.out.println("Enter your last name to play.");
second = in.nextLine();
int length = first.length();
int length2 = second.length();
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + first.charAt(i);
reverse = reverse.substring(0,1).toUpperCase() + reverse.substring(1).toLowerCase();
for ( int i = length2 - 1 ; i >= 0 ; i-- )
reverse2 = reverse2 + second.charAt(i);
reverse2 = reverse2.substring(0,1).toUpperCase() + reverse2.substring(1).toLowerCase();
System.out.println("Your name entered in reverse is: "+reverse+" "+reverse2);
startGame(reverse,reverse2);
}
public static void startGame(String reverse,String reverse2){
Random rnd = new Random ();
Scanner user = new Scanner (System.in);
String guess = "";
String message = "";
int count = 1;
boolean quit = false;
String fullWord = "";
int wins=0;
int loss=0;
int numberOfGames=0;
int guessC = 5;
String usedLetters ="";
String remainingLetters ="";
String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int hinter = 0;
int z = rnd.nextInt(10);
int k = rnd.nextInt(2);
String words[][] = {{"earth","stars","light",
"world","about","again",
"stars","light","music",
"happy","water","amber",
"apple","piano","green",
"mouth","suger","stone",
"japan","china","after","lemon",
"grand",
"lives","twice","print"},{"smile",
"puppy","latin","vegan","phone","april",
"south","house","hangs","woman",
"power","today","india","night","candy",
"forum","birth","other","chris","irish",
"paste","queen","grace","crazy","plant",
"knife","spike","darth","vader","eagle",
"egypt","range","fists","fight","glory",
"March","smart","magic","codes","rolls",
"match","honor","glass","board","teams",
"bully","zebra","under","mango","brain",
"dirty","eight","zeros","train","cycle",
"break","necks","terms","slide","large"},{"stake","guess","wrong","anime","stick","outer","input"},{ "thing","write","white","black"}};
//Prints info of the game and topic that as been selected
System.out.println("Welcome to Hangman"+" "+reverse+" "+reverse2);
//This prints the '-' and spaces for the first run of the game only
for(int index = 0; index < words[z][k].length();index++)
{
Character variableInt = words[z][k].charAt(index);
if(variableInt != ' ')
{
message += "-";
}
else
{
message += " ";
}
}
//Nothing will change, this prints information to the user about his current status in-game.
System.out.println("Secret word: \t\t" + message);
System.out.println("Letters Remaining: " + letters);
System.out.println("Letters Used: ");
System.out.println("Guesses Remaining: " + guessC);
//The loop that will continuously run the game, until the user fails or does not want to play again.
do{
//The following variable's make sure there is not stacking from previous data when the loop runs again.
remainingLetters = "";
count = 0;
//Ask the user for a letter to guess
System.out.println("\nEnter a letter to guess the word): ");
guess = user.nextLine();
//The following for-loop converts ASCII table [A-Z] to actually characters and if the player used a letter it will not show up or add to the string each run of the do-loop.
for(int x = 65; x < 91;x++){
Character current = new Character ((char)x);
String current2 = current.toString();
if(!usedLetters.contains(current2)){
remainingLetters += current;
}
}
//Converts the user's first character to a string which is converted into another character and again converted into a String (Seem's useless) but i used it this way cause i was getting an error.
Character convert = new Character (guess.charAt(0));
Character conv = new Character (convert);
String converted = convert.toString();
//The letters the player uses will be added to a string, if it has not already been added and only if it is a letter.
if(!usedLetters.contains(converted) && conv.isLetter(convert)){
usedLetters+=guess.charAt(0);
}
//Inside this for-loop it turns our word into a String and the user's first character into a string.
for(int index = 0; index < words[z][k].length();index++){
//This is a helper
count++;
//Conversion of variables
Character current2 = new Character ( words[z][k].charAt(index));
String current = current2.toString();
Character current3 = new Character (guess.charAt(0));
String current4 = current3.toString();
String current5 = current4.toUpperCase();
String current6 = words[z][k].toUpperCase();
//If the players gets a letter correct, do the following.
if(current4.equalsIgnoreCase(current))
{
//Add's on to the previous string from where the player got it correct and change it to the correct letter instead of a '-'.
message = message.substring(0,index) + guess + message.substring(index + 1);
}
//If the player gets it wrong and the helper variable is equal to 1 (so that it does not follow the loop of the for-loop and it is not one of the special characters in the game('!' or '?').
if(!current6.contains(current5) && count == 1 && guess.charAt(0) != '?' && guess.charAt(0) != '!'){
guessC--;
}
}
//Prints information to the user of their current topic
//The secret word the player has to guess
System.out.println("Secret word: \t\t" + message.toUpperCase());
//The letters in the alphabet that have not been used yet
System.out.print("\nLetters remaining: ");
System.out.print(remainingLetters.toUpperCase() + "\n\n");
//This will print a message to the user, telling them information on using a hint or the hint itself.
//Letters the user has used since the game session has been running
System.out.print("\nLetters Used: ");
System.out.print(usedLetters.toUpperCase() + "\n");
//The amount of guesses the player has left
System.out.println("\nGuesses Remaining: " +guessC );
//If the player enters a '?' it will do the following.
if(guess.charAt(0) == '?'){
if(hinter <2){
//Displays what is in the array and information about the delay, while losing guesses.
hinter++;
System.out.print("\nHint will appear after next guess! \n");
guessC -=2;
}
}
//If the user guesses the word correct
if(message.equalsIgnoreCase(words[z][k])){
System.out.println("YOU ARE CORRECT! " + words[z][k] + " is correct!");
wins++;
quit = true;
}
//If the user ask to guess the entire word it is stored in a separate variable and make quit equal to true.
if(guess.charAt(0) == '!')
{
System.out.print("\nEnter the secret word: ");
fullWord = user.nextLine();
//if the user guesses the word correct then it will tell the user they are correct and make quit equal to true.
if(fullWord.equalsIgnoreCase(words[z][k])){
System.out.println("YOU ARE CORRECT! " + words[z][k] + " is correct!");
wins++;
quit = true;
}
//If the user does not get it right it will tell the user they are wrong and make quit equal to true.
else{
System.out.println("YOU ARE INCORRECT! the word is: " + words[z][k] + " ");
loss++;
quit = true;
}
}
//If the guesses counter equal 0 then it will tell them that they have lost and make quit equal to true.
if(guessC == 0){
System.out.println("GAME OVER! The secret word was [ " + words[z][k] + " ]!");
loss++;
quit = true;
}
//This is what happens when quit eventually becomes true, the user is asked if they would like to play again.
if(quit == true){
System.out.println("\nWould you like to play again (Y or quit)? ");
System.out.println("\nOr type [stats] to check your work");
guess = user.nextLine();
//If they do want to play again, they will need to enter Y and if they do it will give them another word to guess and resets there information so that there will be no overlap.
if(guess.equalsIgnoreCase("Y")){
quit = false;
z = rnd.nextInt(10);
k = rnd.nextInt(2);
guess = " ";
guessC = 6;
message = "";
usedLetters = "";
hinter = 0;
for(int index = 0; index < words[z][k].length();index++)
{
Character variableInt = words[z][k].charAt(index);
if(variableInt != ' ')
{
message += "-";
}
else
{
message += " ";
}
}
System.out.println("Secret word: \t\t" + message);
System.out.println("Letters Remaining: " + letters);
System.out.println("Letters Used: ");
System.out.println("Guesses Remaining: " + guessC);
}
if(guess.equals("stats")){
printGameStats(wins,loss,numberOfGames);
}
else{
//If the user enters 'N' then they will be told the following and the scanner will be closed.
System.out.println("THANK YOU FOR PLAYING HAVE A GOOD DAY!");
user.close();
}
}
//end of the while loop which will only stop if quit equals true.
}while(quit != true );
}
private static void printGameStats(int wins,int loss,int numberOfGames) {
// Line
System.out.print("+");
printDashes(37);
System.out.println("+");
// Print titles
System.out.printf("| %6s | %6s | %12s |\n",
"WINS", "LOSSES", "GAMES PLAYED");
// Line
System.out.print("|");
printDashes(10);
System.out.print("+");
printDashes(10);
System.out.print("+");
printDashes(10);
System.out.print("+");
printDashes(16);
System.out.print("+");
printDashes(18);
System.out.println("|");
// Print values
System.out.printf("| %6d | %6d | %12d |\n",
wins, loss, numberOfGames);
// Line
System.out.print("+");
printDashes(37);
System.out.println("+");
}
private static void printDashes(int numberOfDashes) {
for (int i = 0; i < numberOfDashes; i++) {
System.out.print("-");
}
}
}

Letter guessing game Java

I have been working on a java guessing game for letters (a-z)! However i have created the game perfectly by using the number 1-26, but i cannot figure out how to convert each integer to a letter ie a = 1, b = 2,....z = 26!
I want the user to try and guess the letter and not the number, but i cannot workout how to do this!
(I know how to generate a random character but i cant implement and link it to each integer within the game correctly)
Random r = new Random();
char targetLetter = (char)(r.nextInt(26) + 'a');
Any help would be greatly appreciated! And i can display my code if it is needed
public class Stack {
public static void main(String[] args) {
Random rand = new Random(); //This is were the computer selects the Target
int guess;
int numGuesses = 0;
int Target;
String userName;
String playagain;
boolean play = true;
int session = 0;
int sessions = 0;
int bestScore = 0;
Scanner consoleIn = new Scanner(System.in);
Scanner name = new Scanner(System.in);
System.out.println("Hello! Please enter your name:\n"); //This is were the user enters his/her name
userName = name.nextLine();
System.out.println("Hello " + userName + " :) Welcome to the game!\n");
while (play = true) {
session++;
Target = rand.nextInt(26) + 1;
System.out.println("Guess a number between 1 and 26? You will have 5 attempts to guess the correct number"); //This is where the computer asks the user to guess the number and how many guesses they will have
do {
guess = consoleIn.nextInt();
numGuesses++;
if (guess > 26)
System.out.println("Error! Above MAXIMUM range");
else if (guess <= 0)
System.out.println("Error! Below MINIMUM range");
else if (guess > Target)
System.out.println("Sorry! Your guess was too high! :)"); //This is to help the player get to the answer
else if (guess < Target)
System.out.println("Sorry! Your guess was too low! :)"); //This is to help the player get to the answer
} while (guess != Target && numGuesses < 5);
if (guess == Target) {
System.out.println("Congratulations " + userName + ", it took you " + numGuesses + " attempts to guess correctly!"); //This tells the player that they got the correct answer and how many attempts it took
sessions++;
} else {
System.out.println("Sorry " + userName + ", You've used up all of your guesses! The correct answer was " + Target + "!"); //This tells the player that they failed to find the number and then tells them what the correct answer
}
{
Scanner answer = new Scanner(System.in);
System.out.println("Would you like another GO " + userName + "? [Y/N]");//This asks the player if they would like to play again
playagain = answer.nextLine();
if (playagain.equalsIgnoreCase("Y")) {//This is what happens if the player opts to play again
play = true;
numGuesses = 0;
} else if (playagain.equalsIgnoreCase("N")) {//This is what happens if the player opts to exit the game
play = false;
System.out.println("Thanks for playing " + userName + "! :) Please come back soon!");
System.out.println("You had " + session + " Goes");
System.out.println("The number of times you guessed correctly: " + sessions + "");
break;
}
}
}
}
}
use arrays of characters
char[] chars = ['A','B','C'...];
and use the random numbers to map to each character
char targetLetter = chars[r.nextInt(26)];
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
System.out.println("Guess the Letter");
String myLetter=scan.nextLine();
//get the letter of myLetter variable then convert to Uppercase
char enteredLetter=Character.toUpperCase(myLetter.charAt(0));
//26 only because the characters array starts with index 0
char[] characters ={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
//I had created a parrallel array symbolizing int value of each letter
int[] range={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26};
//this variable convert user input to one of the array element of range
int userInputToInt=0;
//this variable is for knowing what int[] range array element must the value of userInputToInt fall
int userInputControlLoop=0;
char randomLetter=characters[(int)(Math.random()*26)];
// get the random input of computer convert it to int
int computerInputToInt=0;
//this loop is for getting the int value of randomLetter input by the computer
for(int i=0;i<characters.length;++i)
{
if(randomLetter==characters[i])
{
computerInputToInt=range[i];
}
}
//this loop is for getting the int value of user inputted letter
for(char i:characters)
{
if(enteredLetter==i)
{
userInputToInt=range[userInputControlLoop];
}
++userInputControlLoop;
}
//test the entered letter of user
if(enteredLetter==randomLetter)
{
System.out.println("Correct Guess");
System.out.println("The letter is:"+randomLetter);
}
//test the entered letter of user if greater than computer input
else if(userInputToInt>computerInputToInt)
{
System.out.println("Incorrect Guess");
System.out.println("The letter is too high");
System.out.println("The letter is:"+randomLetter);
}
//test the entered letter of user if lesser than computer input
else if(userInputToInt<computerInputToInt)
{
System.out.println("Incorrect Guess");
System.out.println("The letter is too low");
System.out.println("The letter is:"+randomLetter);
}
}
Use the same method that you do for your random characters. Assuming you have your guessed character as an int variable called "guess", and it has value 1-26 corresponding A-Z:
Random r = new Random();
char targetLetter = (char)(r.nextInt(26) + 'a');
...
int guess = ...
char guessChar = (char)guess + 'a';
if (guessChar == targetLetter) {
System.out.println("Correct!");
} else {
System.out.println("Guess again!")
}
You can implement it in this approach :
1- Create a String alphabet with the characters that you want.
2- declare the size of alphabet as n variable which will control the random generator range.
3- alphabet.charAt(random.nextInt(n)) is a random char from the alphabet.
program code will be :
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int n = alphabet.length();
Random r = new Random();
System.out.println(alphabet.charAt(r.nextInt(n)));
hope will help solve your problem.
public class Picnic1 {
// RULE 0: This code is provided as a working example.
// This rule tests for whether a word starts with the letter 'b' (allowed to the picnic).
public static boolean rule0(char[] array) {
if (array[0] == 'b') {
return true;
}
else {
return false;
}
// itemMessage:
// Return message about whether a particular item is allowed to the picnic.
public static String item ( double[] a){
// This code works, providing output like these examples:
// "banana: true"
// "collie: false"
// It needs to be replaced with a more suitable output.
// Instead it should return, for example:
// "Yes, you can bring a banana to the picnic."
// "No, you cannot bring a collie to the picnic."
if (a[0] == 'b') {
System.out.println("Yes, you can bring a" + 'a' + "to the picnic");
}
else if (a[0] != 'b') {
System.out.print("No, you can not bring a " + 'a' + "to the picnic");
}
}
}
}

How to manually shuffle letters in a String

I am Writing a game/java program that needs to take a word from a .txt file, then jumble the letters up and ask the user to guess what word it is. I am having two problems:
First is that I receive this error message when I run it:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at Proj4.main(Proj4.java:20)
The second problem I am having is jumbling the word. I cannot figure out how to do that without using the shuffle command (which I cannot use).
Here is my code:
import java.util.Scanner;
import java.util.Random;
import java.io.*;
public class Proj4 {
public static void main(String[] args) throws IOException {
Scanner inFile = new Scanner(new File ("words.txt"));
int counter = 0;
while (inFile.hasNext()) {
inFile.nextLine();
counter++;
}
String[] word = new String[counter];
for (int j = 0; j < counter; j++) {
word[j] = inFile.nextLine();
}
int lengthList = Integer.parseInt(word[0]);
Scanner s = new Scanner(System.in);
Random randomNumber = new Random();
int i = randomNumber.nextInt(lengthList); //picks a word at random. assigns to "word"
String currentWord = word[i];//picks a word at random. assigns to "currentWord"
int turnScore = 10, finalScore = 0;
char input;
String guess ="a";
do { //do loop for whole program looping
turnScore = 10;
do { //do loop for guessing correct
do{
System.out.println("Current Puzzle: " + currentWord);
System.out.println("Current points for this word: " + turnScore);
System.out.println("Enter (g)uess, (n)ew word, (h)int, or (q)uit: ");
input = s.nextLine().charAt(0); //assigns input to first letter entered by user
Character.toLowerCase(input); //puts input to lower case
if(input != 'g' && input != 'G' && input != 'h' &&
input != 'H' && input != 'n' && input != 'N' &&
input != 'Q' && input != 'q'){
System.out.println("Invalid Entry. Please input g, n, q or h only! \n ");
}
} while (input != 'g' && input != 'G' && input != 'h' && input != 'H' &&
input != 'n' && input != 'N' && input != 'Q' && input != 'q'); //end do while loop (ask for input)
if (input == 'g') {
System.out.println("Enter Your guess: ");
guess = s.nextLine();
System.out.println("your guess is: " + guess + "\n\nThe word is: " + currentWord);
if (guess.equalsIgnoreCase(currentWord)) {
System.out.println("You Guessed Correct");
System.out.println("Your Score for this word is: " +turnScore );
finalScore = finalScore + turnScore;
}//end if guess = currentWord
else
{
if (turnScore <= 0)
{
turnScore = 0;
}//end if turn score >=0
else
{
turnScore -= 1;
}//end else turn score minus 1.
System.out.println("Nope, Sorry \n\n");
}//end else guess not = to currentWord.
}//end if user input = G.
else if (input == 'n')
{
i = randomNumber.nextInt();
currentWord = word[i];
turnScore = 10;
}//end new word if
else if (input =='h')
{
turnScore = turnScore/2;
Random ranNum = new Random();
int randomLetter = ranNum.nextInt(5);
char hint = currentWord.charAt(randomLetter);
System.out.println("the Letter at spot " + (randomLetter +1) + " is " + hint);
}//end of if input = h
else if (input == 'q')
{
finalScore = finalScore + turnScore;
System.out.println("Goodbye!");
System.out.println("Final Score: " + finalScore);
System.exit(0);
}//end else if for input = Q.
}while (!guess.equalsIgnoreCase(currentWord));
}while (input != 'q');
System.out.println("Your Final Score is: " + finalScore);
System.out.println("Goodbye!");
inFile.close();
}//End main
}//end class
Your exception is caused by these lines of code:
int counter = 0;
while (inFile.hasNext()) {
inFile.nextLine();
counter++;
}
//inFile no longer has next, will break when the for loop is entered
String[] word = new String[counter];
for (int j = 0; j < counter; j++) {
word[j] = inFile.nextLine();
}
The easy way to fix this is to redeclare the inFile and read from beginning again.
The best way to fix this is to use a dynamically sized ArrayList:
int counter = 0;
ArrayList<String> word = new ArrayList<String>();
while (inFile.hasNext()) {
word.add(inFile.nextLine());
counter++;
}
This also makes your randomizing much more easy since you can do something sneaky with it.
Here's the documentation on ArrayList.
The key, not the solution, to your second question lies add(int index, E element)
There is a way to shuffle on the fly as you read. You should figure that out, and if you get stuck, then come back.

Problems with charAt() method in Java

I am trying to make a text-based Hangman in Java.
This is my Java code:
package hangman;
import java.util.Random;
import java.util.Scanner;
import java.lang.String;
public class Hangman {
public static void main(String[] args) {
// TODO code application logic here
Scanner chez = new Scanner(System.in);
Scanner waffle = new Scanner(System.in);
Random randomGenerator = new Random();
StringBuilder displayWord = new StringBuilder("______________________________");
String theWord = null;
String preLetter;
//String sbDisplayWord;
char letter = 0;
int randomNumber;
int lengthOfWord;
int numberOfLetterInWord = 0;
int gDisplay;
int guessWordNumber = 0;
String guessWord;
RandomWord troll = new RandomWord();
randomNumber = randomGenerator.nextInt(12);
//Fill var with the word.
theWord = troll.wordDecide(randomNumber);
System.out.println ("Welcome to Hangman!");
lengthOfWord=theWord.length( );
System.out.println("This word has " + lengthOfWord + " letters.");
System.out.println("You have 20 guesses.");
for (int g =19; g >= 0; g--) {
System.out.println("If you want to guess the word, type 0. If you want to guess a letter, type 1.");
guessWordNumber=chez.nextInt();
if (guessWordNumber==0) {
System.out.println("Enter the word now. Remember, don't capitalize it.");
guessWord=waffle.nextLine();
if (guessWord.equals(theWord)) {
System.out.println("YOU WIN");
System.exit(0);
} else {
System.out.println("Sorry, this wasn't the correct word.");
}
} else if (guessWordNumber==1) {
System.out.println("Please enter the letter you wish to guess with.");
//System.out.println("It will tell you if you have guessed right for any of the letters. If it is blank, that means none of the letters match.");
preLetter=chez.nextLine();
letter=preLetter.charAt(0);
System.out.println("");
for(int i = 0; i <= lengthOfWord -1; i++ ) { //-Eshan
if (letter == theWord.charAt( i )) {
numberOfLetterInWord=i+1;
System.out.println("This letter matches with letter number " + numberOfLetterInWord + " in the word.");
displayWord.setCharAt(i, letter);
} else {
numberOfLetterInWord=i+1;
System.out.println("This letter doesn't match with letter number " + numberOfLetterInWord + " in the word.");
}
}
System.out.println("");
System.out.println("The word so far is " + displayWord);
System.out.println("");
gDisplay = g + 1;
System.out.println("You have " + gDisplay + " guesses left.");
} else {
System.exit(0);
}
}
System.out.println("GAME OVER");
System.exit(0);
}
}
package hangman;
public class RandomWord {
private static String[] wordArray = {
"psychology",
"keratin",
"nostalgia",
"pyromaniac",
"chlorophyl",
"derivative",
"unitard",
"pterodactyl",
"xylophone",
"excommunicate",
"obituary",
"infinitesimal",
"concupiscent",
};
public String wordDecide(int randomNumber) {
String theWord;
theWord = wordArray[randomNumber];
return theWord;
}
}
Netbeans is giving me this error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:695)
at hangman.Hangman.main(Hangman.java:56)
Java Result: 1
This is probably happening when you call charAt(0) on a string of length 0. You should check to see that the string is not empty before calling the method.
You are getting a StringIndexOutOfBoundsException due to the fact the line
guessWordNumber = chez.nextInt();
does not consume newline characters and passes the character through to the line
preLetter = chez.nextLine();
which then doesn't block as it will have already received input. This assigns an empty String to preLetter resulting in the exception. You can use Scanner#nextLine to consume this character:
guessWordNumber = Integer.parseInt(chez.nextLine());

Categories