Loop issue with use of if statement - java

I have this hangman program but have an issue with asking the user if they want to play again, it always just ends the program. How can i fix this issue. Thanks for future reply's.
package hangman. I hope editing is okay with this
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Hangman {
static Scanner keyboard = new Scanner(System.in);
static int size, size2;
static boolean play = false;
static String word;
static String[] ARRAY = new String[0];
static String ANSI_RESET = "\u001B[0m";
static String ANSI_BLUE = "\u001B[34m";
static String ANSI_GREEN = "\u001B[32m";
static String ANSI_RED = "\u001B[31m";
static String ANSI_LIGHTBLUE = "\u001B[36m";
//^declarations for variables and colors for display^
public static void main(String[] args) {
randomWordPicking();
//^calls method^
}
public static void setUpGame() {
System.err.printf("Welcome to hangman.\n");
try {
Scanner scFile = new Scanner(new File("H:\\HangMan\\src\\hangman\\HangMan.txt"));
String line;
while (scFile.hasNext()) {
line = scFile.nextLine();
Scanner scLine = new Scanner(line);
size++;
}
ARRAY = new String[size];
Scanner scFile1 = new Scanner(new File("H:\\HangMan\\src\\hangman\\HangMan.txt"));
while (scFile1.hasNext()) {
String getWord;
line = scFile1.nextLine();
Scanner scLine = new Scanner(line);
word = scLine.next();
ARRAY[size2] = word;
size2++;
//calls method for picking word^
}
} catch (FileNotFoundException e) {
System.out.println(e);
}
}
public static void randomWordPicking() {
setUpGame();
int LEFT = 6;
do {
int random = (int) (Math.random() * ARRAY.length);
//^genertates a random number^
String randomWord = ARRAY[random];
String word = randomWord;
//^chosses a random word and asgins it to a variable^
char[] ranWord = randomWord.toCharArray();
char[] dash = word.toCharArray();
//^Creates a char array for the random word chosen and for the dashs which are displayed^
for (int i = 0; i < dash.length; i++) {
dash[i] = '-';
System.out.print(dash[i]);
//^displays dashs to the user^
}
for (int A = 1; A <= dash.length;) {
System.out.print(ANSI_BLUE + "\nGuess a Letter: " + ANSI_RESET);
String userletters = keyboard.next();
//^gets user input^
if (!userletters.equalsIgnoreCase(randomWord)) {
//^allows program to enter loop if user has entered a letter^
for (int i = 0; i < userletters.length(); i++) {
char userLetter = userletters.charAt(i);
String T = Character.toString(userLetter);
for (int B = 0; B < ranWord.length; B++) {
//^converts users input to a char and to a string^
if (userLetter == dash[B]) {
System.err.println("This " + userLetter + "' letter already exist");
B++;
//^tells user if the letter they entered already exists^
if (userLetter == dash[B - 1]) {
break;
}
} else if (userLetter == ranWord[B]) {
dash[B] = userLetter;
A--;
}
}
if (!(new String(ranWord).contains(T))) {
LEFT--;
System.out.println("You did not guess a correct letter, you have " + LEFT + " OF "
+ dash.length + " trys left to guess correctly");
}
//^shows how many trys the user has left to get the word right before game ends^
System.out.println(dash);
if (LEFT == 0) {
System.out.println("The word you had to guess was " + word);
break;
}
//^shows the user the word if they didnt guess correctly^
}
} else {
System.out.println(ANSI_GREEN + "\nYou have guessed the word correctly!" + ANSI_RESET);
break;
}
if (LEFT == 0) {
break;
}
if ((new String(word)).equals(new String(dash))) {
System.out.println(ANSI_GREEN + "\nYou have guessed the word correctly!" + ANSI_RESET);
break;
}
}
//^if user enters the word it will check and then display that they got the word correct^
System.out.println("Play agian? (y/n)");
String name = keyboard.next();
//^asks user if they want to play again^
if (name.equalsIgnoreCase("n")) {
play = true;
return;
}
//^stops program if user enters n to stop game^
} while (play = false);
}
}

If you want to compare two variables, do not use = operator, which means assignment. Use == instead. Additionally, in your case it should be !=:
while (play != false)

You should use
while (!play)
instead of
while (play = false)

Related

Guessing letter without having to capitalize input

I am new to this and I am having hard time with this code. I made a hangman game but I am having issues with the words that have a capital letter. If I don't input a capital letter the letter will not appear.
Here is my code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Hangman {
static ArrayList<String> words = new ArrayList<>();
static boolean isCorrect;
private static Scanner input;
private static Scanner input2;
public static void main(String[] args) {
File filename = new File("hangman.txt");
if (!filename.exists()) {
System.out.println(filename.getAbsolutePath());
System.out.println(filename + " does not exist.");
System.exit(1);
}
try {
input2 = new Scanner(filename);
while (input2.hasNext()) {
words.add(input2.next());
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
input2.close();
input = new Scanner(System.in);
String playStarts = "y";
int wins = 0;
int loses = 0;
final int MAX_GUESSES = 11;
List<String> usedWords = new ArrayList<>();
while (playStarts.equals("y")) {
String word = getWord();
usedWords.add(word);
String secretWord = getSecretWord(word);
int missCount = 0;
while (!word.equals(secretWord)) {
System.out.print("(Guess) Enter a letter in word " + secretWord + " > ");
char ch = input.next().charAt(0);
if (!isAlreadyInWord(secretWord, ch)) {
secretWord = getGuess(word, secretWord, ch);
if (!isCorrect) {
System.out.print(ch + " is not in the word.");
missCount++;
System.out.println(" You missed "+ missCount + " times");
}
} else {
System.out.println(ch + " is already in word.");
}
if (missCount == MAX_GUESSES) {
System.out.println("You reached max number of guesses.");break;
}
}
if (missCount == MAX_GUESSES) {
loses++;
} else {
wins++;
}
System.out.println("The word is " + word + ". You missed " + missCount + " times");
System.out.println("Do you want to guess another word? Enter y or n >");
playStarts = input.next();
}
System.out.println("Number of wins is " + wins + ".");
System.out.println("Number of loses is " + loses + ".");
System.out.println("Used words:");
for (String word : usedWords) {
System.out.println(word);
}
input.close();
}
public static String getWord() {
return words.get((int) (Math.random() * words.size()));
}
public static String getSecretWord(String word) {
String hidden = "";
for (int i = 0; i < word.length(); i++) {
hidden += "*";
}
return hidden;
}
static public String getGuess(String word, String secretWord, char ch) {
isCorrect = false;
StringBuilder s = new StringBuilder(secretWord);
for (int i = 0; i < word.length(); i++) {
//I think the issue is in this section of the code:
if (ch == word.charAt(i) && s.charAt(i) == '*') {
isCorrect = true;
s = s.deleteCharAt(i);
s = s.insert(i, ch);
}
}
return s.toString();
}
public static boolean isAlreadyInWord(String secretWord, char ch) {
for (int i = 0; i < secretWord.length(); i++) {
if (ch == secretWord.charAt(i)) {
return true;
}
}
return false;
}
}
The code works fine but I just have an issue with the capitalization.
If your speculation be correct, the comparing the lowercase of both sides of the equation should fix the problem:
if (Character.toLowerCase(ch) == Character.toLowerCase(secretWord.charAt(i)) {
return true;
}
Better yet, you can lowercase the user character input when it actually happens:
System.out.print("(Guess) Enter a letter in word " + secretWord + " > ");
char ch = input.next().toLowerCase().charAt(0);
There are some handy functions in the Character class that you can use (Character.toUpperCase() and toLowerCase()) that can help you compare whether the characters match.
if (Character.toLowerCase(ch) == Character.toLowerCase(word.charAt(i)) && s.charAt(i) == '*') will always be checking two lowercase letters, so the case of neither ch or word.charAt(i) will matter.

How to scramble a word that is picked randomly from a text file

I am attempting to write a program that picks a random word from a text file, scrambles it, and allows the user to unscramble it by swapping 2 index locations at a time.
I have the program to the point where it grabs a random word from the text file and prints it out with the index numbers above it.
I am having trouble figuring out how to:
Get the word scrambled before it prints out on screen, and
How to get the user to be able to loop through swapping 2 indexes at a time until the word is unscrambled.
Is there a method I can write that will perform these actions?
Here is my code so far.
import java.io.*;
import java.util.*;
public class Midterm { // class header
public static void main(String[] args) { // Method header
int option = 0;
Scanner input = new Scanner(System.in);
int scrambled;
int counter = 0;
int index1;
int index2;
String[] words = readArray("words.txt");
/*
* Picks a random word from the array built from words.txt file. Prints
* index with word beneath it.
*/
int randWord = (int) (Math.random() * 11);
for (int j = 0; j < words[randWord].length(); j = j + 1) {
System.out.print(j);
}
System.out.print("\n");
char[] charArray = words[randWord].toCharArray();
for (char c : charArray) {
System.out.print(c);
}
/*
* Prompt the user for input to play game or quit.
*/
System.out.println("\n");
System.out.println("Enter 1 to swap a par of letters.");
System.out.println("Enter 2 to show the solution and quit.");
System.out.println("Enter 3 to quit.");
if (input.hasNextInt()) {
option = input.nextInt();
counter++;
}
else {
option = 3;
}
System.out.println("");
if (option == 1) {
System.out.println("Enter the two index locations to swap separated by a space. ");
index1 = 0;
index2 = 0;
if (input.hasNextInt()) {
index1 = input.nextInt();
}
else {
System.out.println("Please enter only numbers.");
}
if (input.hasNextInt()) {
index2 = input.nextInt();
}
else {
System.out.println("Please enter only numbers.");
}
}
}
// end main
public static String[] readArray(String file) {
// Step 1:
// Count how many lines are in the file
// Step 2:
// Create the array and copy the elements into it
// Step 1:
int ctr = 0;
try {
Scanner s1 = new Scanner(new File(file));
while (s1.hasNextLine()) {
ctr = ctr + 1;
s1.nextLine();
}
String[] words = new String[ctr];
// Step 2:
Scanner s2 = new Scanner(new File(file));
for (int i = 0; i < ctr; i = i + 1) {
words[i] = s2.next();
}
return words;
} catch (FileNotFoundException e) {
}
return null;
}
}
I made some pretty major modifications to your code, including adding a scrambler method. The program is almost perfect, its just that your file "words.txt" can not hold words with repeat letters. For example, yellow, green, and purple won't unscramble correctly, but white, gray, blue, orange, or red will work fine. Other than that, the program works well. It chooses a random word, then when it is solved, chooses a different word, changing the last word to null, so it does not get picked again. Here's the program:
import java.io.*;
import java.util.*;
public class Experiments { // class header
private static String[] words = readArray("/Users/UserName/Desktop/words.txt"); //change to your location of the file
public static void main(String[] args) { // Method header
int option = 0;
Scanner input = new Scanner(System.in);
int counter = 0;
String scrambledWord;
int index1;
int index2;
Random rand = new Random();
int randWord = rand.nextInt(words.length);
for (int j = 0; j < words[randWord].length(); j += 1) {
System.out.print(j);
}
System.out.print("\n");
scrambledWord = scrambler(words[randWord]);
System.out.println(scrambledWord);
System.out.println("\n");
System.out.println("Enter 1 to swap a pair of letters.");
System.out.println("Enter 2 to show the solution and quit.");
System.out.println("Enter 3 to quit.");
option = input.nextInt();
if (option == 1) {
while (!scrambledWord.equals(words[randWord])) {
index1 = 0;
index2 = 0;
boolean validOption = false;
System.out.println("Enter the two index locations to swap separated by a space.");
while (!validOption) {
if (input.hasNextInt()) {
index1 = input.nextInt();
index2 = input.nextInt();
validOption = true;
}
else {
System.out.println("Please enter only numbers.");
validOption = false;
break;
}
}
String letter1 = scrambledWord.substring(index1, index1+1);
String letter2 = scrambledWord.substring(index2, index2+1);
System.out.println("replacing " + letter1 + " with " + letter2 + "...");
if (index1 < index2) {
scrambledWord = scrambledWord.replaceFirst(letter2, letter1);
scrambledWord = scrambledWord.replaceFirst(letter1, letter2);
} else {
scrambledWord = scrambledWord.replaceFirst(letter1, letter2);
scrambledWord = scrambledWord.replaceFirst(letter2, letter1);
}
System.out.println();
for (int j = 0; j < words[randWord].length(); j += 1) {
System.out.print(j);
}
System.out.println("\n"+scrambledWord);
System.out.println();
counter++;
if (scrambledWord.equals(words[randWord])){
System.out.println("You did it! The word was " + words[randWord]);
System.out.println("You got it with " + counter + " replacements!");
words[randWord] = null;
if (words.length == 0){
System.out.println("I'm all out of words. You win!");
System.exit(0);
} else {
main(args);
}
}
}
} else if (option == 2) {
System.out.println(words[randWord]);
System.exit(0);
} else {
System.exit(0);
}
input.close();
}
//scrambles the word given to it
private static String scrambler(String word) {
String scrambled = "";
Random rand = new Random();
int length;
int index;
String letter;
String firststring;
String secondstring;
while (word.length()>0) {
length = word.length();
index = rand.nextInt(length);
letter = word.substring(index, index+1);
firststring = word.substring(0, index);
secondstring = word.substring(index+1);
word = firststring + secondstring;
scrambled += letter;
}
return scrambled;
}
public static String[] readArray(String file) {
int ctr = 0;
try {
Scanner s1 = new Scanner(new File(file));
while (s1.hasNextLine()) {
ctr = ctr + 1;
s1.nextLine();
}
String[] words = new String[ctr];
// Step 2:
Scanner s2 = new Scanner(new File(file));
for (int i = 0; i < ctr; i = i + 1) {
words[i] = s2.next();
}
return words;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
And here's the list of words in the file words.txt(I pretty much wrote down whatever popped into my head that did not have repeat letters):
orange
red
brown
black
white
blue
tiger
horse
bugs
stack
overflow
pathfinder
extra
zealous
wisdom
under
above
death
life
second
first
frost
forest
These are obviously not the only words that can go in, you can add as many as you want, as long as they do not have 2 occurrences of the same letter.
You are reading the file incorrectly. Do
public static String[] readArray(String file) {
int ctr = 0;
try {
Scanner s1 = new Scanner(new File(file));
while (s1.hasNext()) {
ctr = ctr + 1;
s1.next();
}
//..rest of code

How to return a string?

import java.util.*;
public class HangManP5
{
public static void main(String[] args)
{
int attempts = 10;
int wordLength;
boolean solved;
Scanner k = new Scanner(System.in);
System.out.println("Hey, what's your name?");
String name = k.nextLine();
System.out.println(name+ ", hey! This is a hangman game!\n");
RandomWord(word);
int len = word.length();
char[] temp = new char[len];
for(int i = 0; i < temp.length; i++)
{
temp[i] = '*';
}
System.out.print("\n");
System.out.print("Word to date: ");
while (attempts <= 10 && attempts > 0)
{
System.out.println("\nAttempts left: " + attempts);
System.out.print("Enter letter: ");
String test = k.next();
if(test.length() != 1)
{
System.out.println("Please enter 1 character");
continue;
}
char testChar = test.charAt(0);
int foundPos = -2;
int foundCount = 0;
while((foundPos = word.indexOf(testChar, foundPos + 1)) != -1)
{
temp[foundPos] = testChar;
foundCount++;
len--;
}
if(foundCount == 0)
{
System.out.println("Sorry, didn't find any matches for " + test);
}
else
{
System.out.println("Found " + foundCount + " matches for " + test);
}
for(int i = 0; i < temp.length; i++)
{
System.out.print(temp[i]);
}
System.out.println();
if(len == 0)
{
break; //Solved!
}
attempts--;
}
if(len == 0)
{
System.out.println("\n---------------------------");
System.out.println("Solved!");
}
else
{
System.out.println("\n---------------------------");
System.out.println("Sorry you didn't find the mystery word!");
System.out.println("It was \"" + word + "\"");
}
}
public static String RandomWord(String word)
{
//List of words
Random r = new Random();
int a = 1 + r.nextInt(5);
if(a == 1)
{
word=("Peace");
}
if(a == 2)
{
word=("Nuts");
}
if(a == 3)
{
word=("Cool");
}
if(a == 4)
{
word=("Fizz");
}
if(a == 5)
{
word=("Awesome");
}
return (word);
}
}
Ok, so this is my code for a hangman game, the only thing I have left to do is to get my program to randomize one of the words, which it should do in the method successfully. But the only problem I'm having is getting the String variable "word" to go back to the main class (there are errors underlining all the "word" variables in the main class).
If I could get help with either this or another way to produce a random word from a list, that would be amazing.
In java, parameters are passed by value and not by reference. Therefore, you cannot change the reference of a parameter.
In your case, you need to do:
public static String getRandomWord() {
switch(new Random().nextInt(5)) {
case 0:
return "Peace";
case 1:
return "Nuts";
// ...
default:
throw new IllegalStateException("Something went wrong!");
}
}
And in main:
// ...
String word = getRandomWord();
int len = word.length();
// ...
You can't modify the caller's reference.
RandomWord(word);
needs to be something like
word = RandomWord(word);
Also, by convention, Java methods start with a lower case letter. And, you could return the word without passing one in as an argument and I suggest you save your Random reference and use an array like
private static Random rand = new Random();
public static String randomWord() {
String[] words = { "Peace", "Nuts", "Cool", "Fizz", "Awesome" };
return words[rand.nextInt(words.length)];
}
And then call it like
word = randomWord();

Palindrome coding

I am trying to create a Palindrome tester in java using a method.. This is what I have so far. It is so close I just can't figure out why it won't say that it IS a palindrome and reverse it.
System.out.println("Fun with Palindromes!!");
Scanner in = new Scanner(System.in);
System.out.println("Enter the potential palindrome (or enter exit to quit): ");
String x = in.nextLine();
while(!x.equals("exit"))
{
String t = x.toLowerCase();
String u = CleanUpString(t);
Boolean wordCheck = checkPalindrome(u);
int wordCount = x.length();
String rev = "";
for(int i = 0; i <x.length(); i++)
{
rev = x.charAt(i)+rev;
}
if(wordCheck == true)
{
System.out.println("The orginal string\"" + u + "\" contains" + wordCount + "characters." );
System.out.println("The converted string\"" + rev + "\"is a palindrome");
}
else if(wordCheck == false)
{
System.out.println("The string \"" + u + "\" contains " + wordCount + " characters");
System.out.println("\"" + rev + "\" is not a palindrome");
}
System.out.println("\nEnter the potential palindrome, or enter exit to quit: ");
x = in.nextLine();
}
}
public static String CleanUpString(String words)
{
words = words.replace(".","");
words = words.replace("," ,"");
words = words.replace(":","");
words = words.replace("!","");
return words;
}
public static boolean checkPalindrome(String baseball)
{
String rev = "";
for(int i = 0; i<baseball.length()-1; i++)
{
rev = baseball.charAt(i) + rev;
}
if(rev.equals(baseball))
return true;
else
return false;
}
}
Here is the code I used to determine whether a string is Palindrome String or not:
private static boolean checkPalindrome(String str){
if (str == null)
return false;
int len = str.length();
for (int i=0;i<len/2 ; i++){
if (str.charAt(i) != str.charAt(len - i - 1)){
return false;
}
}
return true;
}
For reversing strings, you can simply use:
String reverse = new StringBuffer(string).reverse().toString();
Hope these can help you.
Use StringUtils for this
import org.apache.commons.lang.StringUtils;
boolean isPalindrome(String word) {
return StringUtils.reverse(word).equals(word);
}
Here is another option
public class PalindromeTester {
public static void main(String[] args) {
try {
String s = args[0];
int i = args[0].length()-1;
int i2 = args[0].length();
char [] chrs = new char[i2];
for ( int i3 = i; i3 > -1; i3-- ) {
chrs[i2-i3-1] = (s.charAt(i3) );
}
String s2 = String.valueOf(chrs);
if ( s2.equals(s) ) {
System.out.println( s + " is a palindrome!");
} else {
System.out.println( s + " is not a palindrome");
}
} catch ( ArrayIndexOutOfBoundsException e ) {
System.out.println("Please enter at least one letter or digit!");
}
}
}
Here's how I did it:
public class palindromeTWO
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int right = 0;
int left = 1;
System.out.println("Please enter a word: ");
String word = scan.next();
int word_length = word.length();
while(word.charAt(right) == word.charAt(word_length - left) && left < (word_length / 2))
{
left++;
right++;
}
if(word.charAt(right) == word.charAt(word_length - left))
{
System.out.println("'" + word + "'" + " is a palindrome!");
}
else
{
System.out.println("'" + word + "'" + " is NOT a palindrome.");
}
}
}
1st implementation using recursion -
import java.util.ArrayList;
import java.util.stream.Collectors;
public class PalindromeManager {
private static String str = "ehcache";
private static ArrayList<String> list = new ArrayList<>();
public static void main(String[] args) {
test(str);
String output = list.stream().collect(Collectors.joining());
System.out.println(output);
if (output.equals(str)) {
System.out.println("it was palindrome");
} else {
System.out.println("Nope! it wasn't");
}
}
private static void test(String str) {
if (str.length() <= 0) {
return;
}
String lastChar = "" + str.charAt(str.length() - 1);
list.add(lastChar);
test(str.substring(0, str.length() - 1));
}
}
2nd implementation using iteration -
public class PalindromeManager2 {
private static String str = "ehcache";
public static void main(String[] args) {
int startIndex = 0;
int lastIndex = str.length() - 1;
boolean result = true;
while (true) {
if (startIndex >= lastIndex) {
break;
}
char first = str.charAt(startIndex);
char last = str.charAt(lastIndex);
/*if (first == ' ') {
startIndex++;
continue;
}
if (last == ' ') {
lastIndex--;
continue;
}*/
if (first != last) {
result = false;
break;
}
startIndex++;
lastIndex--;
}
if (result) {
System.out.println("Yes! It was");
} else {
System.out.println("Nope! it wasn't");
}
}
}
In checkPalindrome method change the condition of for loop from i<baseball.length()-1 to i<baseball.length().

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