Getting an error! String.charAt(Unknown Source) ???
I'm getting an error i really don't know why:
ERROR:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at Hangman.checkLetter(Hangman.java:172)
at Hangman.userGuess(Hangman.java:111)
at Hangman.main(Hangman.java:39
CODE:
for(int i = 0; i< MAX_WORD_LENGTH; i++){
if(word.charAt(i) == userLetter){//checking if the letter is in the word
wordSoFar[i] = userLetter;
}//end if
}//end for
Re: Getting an error! String.charAt(Unknown Source) ???
Quote:
StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at Hangman.checkLetter(Hangman.java:172)
The error says that the index used in charAt() on line 172 is past the end of the String. Check that the String has a length > 0 before trying to get the first character in the String.
One way would be to use the length of the String to control the for loop instead of some variable.
Re: Getting an error! String.charAt(Unknown Source) ???
Even that still gives me the error. I'm wondering if it has anything to do with variable "i" being automatically bigger than my word before it can run through?
Re: Getting an error! String.charAt(Unknown Source) ???
Post the new code and the full text of the error message.
Re: Getting an error! String.charAt(Unknown Source) ???
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(String.java:686)
at Hangman.userGuess(Hangman.java:130)
at Hangman.main(Hangman.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Nativ e Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Native MethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(De legatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.ru nCommand(JavacCompiler.java:272)
Code:
for(int i = 0; i< wordSoFar.length; i++){
if(word.charAt(i) == userLetter){ <--------- this is line 130
wordSoFar[i] = userLetter;
}
Note:
Word and wordSoFar are the same length, word is a string and wordSoFar is a char array this is part of my hangman game.
Re: Getting an error! String.charAt(Unknown Source) ???
There are two different variables used in the posted code. The code should use the same one in both places.
wordSoFar
and
word
Use the length of word to control the loop. Get rid of wordSoFar
Print out the length of word to see how long it is.
Re: Getting an error! String.charAt(Unknown Source) ???
The length of word is always 6 and when i try use word.length it gives me an error saying cant find symbol: variable length for this :
for(int i = 0; i< word.length; i++){
if(word.charAt(i) == userLetter){
wordSoFar[i] = userLetter;
}
}
Re: Getting an error! String.charAt(Unknown Source) ???
If word is a String object, you need to use a method (ends with ()s) to get its length. The String class does not have a length member.
Re: Getting an error! String.charAt(Unknown Source) ???
So what would i write as the method then?
Re: Getting an error! String.charAt(Unknown Source) ???
See the String class's API doc for its methods:
Java Platform SE 7
Re: Getting an error! String.charAt(Unknown Source) ???
thanks for that. but know my program just ends when i get to that point so idk.
Re: Getting an error! String.charAt(Unknown Source) ???
Quote:
my program just ends
Please explain.
Re: Getting an error! String.charAt(Unknown Source) ???
Uhm it doesn't execute that chunk of code by the looks of it, it just skips right by it like it doesn't exist?
--- Update ---
This is my entire code so far:
Code java:
/* Author: Brendon Drury
* Description: This is a program for a hangman game that can be played
* between 1-3 times with 12 guesses with a random word choosen each time.
* Date: 09/03/2013
*/
import java.util.Scanner;
import java.lang.String;
public class Hangman{
//--------------------------------------------------------------------------------------------------
// The main mehod will be using minimal code but will call each sub method in sequence to run the
// program bit by bit.
//--------------------------------------------------------------------------------------------------
public static void main(String[] args){
final int MAX_GAMES = 3;
String word = "";
int totalGames = 0;
char userLetter = ' ';
String temp = "";
char[] guessedLetters = new char[26];
String alphabet = "abcdefghijklmnopqrstuvwxyz";
final int MAX_WRONG_GUESSES = 12;
int remainingGuesses = 12;
final int MAX_WORD_LENGTH = 6;
char[] wordSoFar = new char[MAX_WORD_LENGTH];
gamesToBePlayed(totalGames, MAX_GAMES);//this well call the first sub method gamesToBePlayed to be carried out
while(totalGames >= 0){//this loop will keep going until the amount of games has reached 1
chooseWord(word);//calls the chooseWord method to be used
System.out.println("Lets Play Hangman! (The word is the name of an Animal)");
setGuessedLetters(guessedLetters);
setWordSoFar(wordSoFar);
while(remainingGuesses >= 0){//Will loop until all guesses reach 0
userGuess(guessedLetters, remainingGuesses, userLetter, MAX_WORD_LENGTH, word,alphabet,wordSoFar);//calls the
//userGuess method to take place
}
}
totalGames--;//takes one away from totalGames so after each game is taken through
}//end main
//--------------------------------------------------------------------------------------------------
// This method will be used to get input from the user that will set the variable that will give
// the amount of games that will be played between 1-3.
//--------------------------------------------------------------------------------------------------
public static int gamesToBePlayed(int totalGames, int MAX_GAMES){
while((totalGames > MAX_GAMES) || (totalGames <= 0)){//loops untill totalGames is between 1-3
totalGames = readInt("Enter the number of games you want to be played ( max of 3 games ) eg. 1 - 3");//reads
//in input from the user asking for an int between 1-3
}
return totalGames;
}//end gamesToBePlayed
//--------------------------------------------------------------------------------------------------
// This method is used to select a word at random from a string array to be used in the game and
// sets the wordSoFar variable for the next method.
//--------------------------------------------------------------------------------------------------
public static String chooseWord(String word){
String[] wordList = {"friday","apples","monkey","baboon","doctor","cousin","canada","office",
"poodle","poster"};// String Array holding 10 different names to be choosen from for the game
java.util.Random generator = new java.util.Random();//importing the random generator
int randomNum = generator.nextInt(wordList.length);//setting the randomNum variable to get a random number
word = wordList[randomNum];//using the randomNum to select the word from the array
return word;
}//end chooseWord
//--------------------------------------------------------------------------------------------------
// This method is used to do most of the in game things including gather the users guesses
// and sorting them all into the nessescary categories.
//--------------------------------------------------------------------------------------------------
public static void userGuess(char[] guessedLetters, int remainingGuesses, char userLetter, int MAX_WORD_LENGTH,
String word, String alphabet, char[] wordSoFar){
String tempLetters = new String(guessedLetters);//converting char array to string to compare later in method
userLetter = readChar(" Enter your guess? ");//reads in the users string input and sets to variable temp
for(int k =0; k < 26; k++){//for loop for checking if letter guessed before
while(userLetter == tempLetters.charAt(k)){//while input is in tempLetters will ask for user guess
userLetter = readChar(" Enter your guess? ");//reads in the users char input
}
}
for(int l = 0; l< word.length(); l++){
if(word.charAt(l) == userLetter){//checking if the letter is in the word
wordSoFar[l] = userLetter;
System.out.println("Correct");
}else{
remainingGuesses--;
}
}//end for
for(int p =0 ; p<tempLetters.length(); p++){
if(userLetter == alphabet.charAt(p)){
guessedLetters[p] = userLetter;
}//end if
}//end for
for(int h =0 ; h<word.length(); h++){
if(wordSoFar[h] == word.charAt(h)){
System.out.println("Well done you've won!");
break;
}//end if
}//end for
System.out.print("Letters guessed: ");//output guessed letters
System.out.println(guessedLetters);
System.out.print("Word so far: ");//output the word so far
System.out.println(wordSoFar);
System.out.println("Guesses left: " + remainingGuesses);//output the amount of guesses left
}//end userGuess
//--------------------------------------------------------------------------------------------------
// This method is used to get an integer input from the user and will be used in the gamesToBePlayed
// method to get the total amount of games that will be played .
//--------------------------------------------------------------------------------------------------
public static int readInt(String prompt){
System.out.println(prompt);
int userInput = 0;
try{
Scanner keyboard = new Scanner(System.in);
userInput = keyboard.nextInt();
}
catch(Exception e){
System.out.println("Not a number between 1 - 3");
}
return userInput;
}//end readInt
//--------------------------------------------------------------------------------------------------
// This method will be used to get a Char input from the user which will be used in the userGuess
// guess mehod for the letter that player is guessing.
//--------------------------------------------------------------------------------------------------
public static char readChar(String prompt){
char tempChar;
String tempString;
System.out.println(prompt);
Scanner keyboard = new Scanner(System.in);
tempString = keyboard.nextLine();
tempChar = tempString.charAt(0);
return tempChar;
}//end readChar
//--------------------------------------------------------------------------------------------------
// This method will be used to set the wordsofarto underscores and return it
//--------------------------------------------------------------------------------------------------
public static char[] setWordSoFar( char[] wordSoFar){
for(int i=0;i<wordSoFar.length;i++){//for loop to set all chars to underscores
wordSoFar[i] = '_';//set all chars to underscores
}//end for
return wordSoFar;
}
//--------------------------------------------------------------------------------------------------
// This method will be used to set huessedLetters to spaces and return it
//--------------------------------------------------------------------------------------------------
public static char[] setGuessedLetters(char[] guessedLetters){
for(int j = 0; j<26; j++){//create for loop to replace all chars in guessedLetters
guessedLetters[j] = ' ';//setting all chars in variable to spaces
}//end for
return guessedLetters;
}
}//end class
Re: Getting an error! String.charAt(Unknown Source) ???
Try debugging the code by adding some println statements that print out messages as the code executes and prints out the values of the variables that control the execution flow.
Please edit your post and wrap your code with
[code=java]
<YOUR CODE HERE>
[/code]
to get highlighting and preserve formatting.
Re: Getting an error! String.charAt(Unknown Source) ???
I put prints for variables and other things in between the for and if statements and they dont print so it has something to do with the following for loop?
Code java:
for(int l = 0; l< word.length(); l++){
if(word.charAt(l) == userLetter){//checking if the letter is in the word
wordSoFar[l] = userLetter;
System.out.println("Correct");
}else{
remainingGuesses--;
}
}//end for
Re: Getting an error! String.charAt(Unknown Source) ???
What are the values of these as the loop executes: word.charAt(l) and userLetter
Also print out this: word.length()
Re: Getting an error! String.charAt(Unknown Source) ???
word is a six letter word from a random list and userLetter is an input between a-z and i've being trying each and every letter
Re: Getting an error! String.charAt(Unknown Source) ???
What prints out when you added the println statements?
Re: Getting an error! String.charAt(Unknown Source) ???
ohh wait i found the problem my word is printing as nothing so ill look for why it is nothing.
Re: Getting an error! String.charAt(Unknown Source) ???
One potential problem I see is having class variables and local/method variables with the same name.
There are a lot of variables named: word. Change the class variable to have a different name from the names used in the methods. That will make it easier to use the editor's Find function to find where it is use.
Re: Getting an error! String.charAt(Unknown Source) ???
thanks for your help so far i just have one last thing as i found the problem and have worked on my code. I can't get my remaining guesses to work properly, i have it set to take 1 off when the letter is not in the word but sometimes it adds back on to remaining guesses and never goes lower than 11?
Code java:
/* Author: Brendon Drury
* Description: This is a program for a hangman game that can be played
* between 1-3 times with 12 guesses with a random word choosen each time.
* Date: 09/03/2013
*/
import java.util.Scanner;
import java.lang.String;
public class Hangman{
//--------------------------------------------------------------------------------------------------
// The main mehod will be using minimal code but will call each sub method in sequence to run the
// program bit by bit.
//--------------------------------------------------------------------------------------------------
static String word = "";
static boolean win = false;
static final int MAX_GAMES = 3;
static int totalGames = 0;
public static void main(String[] args){
char userLetter = ' ';
String temp = "";
char[] guessedLetters = new char[26];
String alphabet = "abcdefghijklmnopqrstuvwxyz";
final int MAX_WRONG_GUESSES = 12;
int remainingGuesses = 12;
final int MAX_WORD_LENGTH = 6;
char[] wordSoFar = new char[MAX_WORD_LENGTH];
gamesToBePlayed();//this well call the first sub method gamesToBePlayed to be carried out
while(totalGames >= 1){//this loop will keep going until the amount of games has reached 1
totalGames--;//takes one away from totalGames so after each game is taken through
chooseWord();//calls the chooseWord method to be used
System.out.println("Lets Play Hangman! (The word is the name of an Animal)");
setGuessedLetters(guessedLetters);
setWordSoFar(wordSoFar);
win = false;
while((remainingGuesses >= 0) && (win == false)){//Will loop until all guesses reach 0
userGuess(guessedLetters, remainingGuesses, userLetter, MAX_WORD_LENGTH,alphabet,wordSoFar);//calls the
//userGuess method to take place
}
}
}//end main
//--------------------------------------------------------------------------------------------------
// This method will be used to get input from the user that will set the variable that will give
// the amount of games that will be played between 1-3.
//--------------------------------------------------------------------------------------------------
public static void gamesToBePlayed(){
while((totalGames > MAX_GAMES) || (totalGames <= 0)){//loops untill totalGames is between 1-3
totalGames = readInt("Enter the number of games you want to be played ( max of 3 games ) eg. 1 - 3");//reads
//in input from the user asking for an int between 1-3
}
}//end gamesToBePlayed
//--------------------------------------------------------------------------------------------------
// This method is used to select a word at random from a string array to be used in the game and
// sets the wordSoFar variable for the next method.
//--------------------------------------------------------------------------------------------------
public static void chooseWord(){
String[] wordList = {"friday","teapot","monkey","flower","browny","cousin","budget","exotic",
"garlic","poster"};// String Array holding 10 different names to be choosen from for the game
java.util.Random generator = new java.util.Random();//importing the random generator
int randomNum = generator.nextInt(wordList.length);//setting the randomNum variable to get a random number
word = wordList[randomNum];//using the randomNum to select the word from the array
}//end chooseWord
//--------------------------------------------------------------------------------------------------
// This method is used to do most of the in game things including gather the users guesses
// and sorting them all into the nessescary categories.
//--------------------------------------------------------------------------------------------------
public static void userGuess(char[] guessedLetters, int remainingGuesses, char userLetter, int MAX_WORD_LENGTH,
String alphabet, char[] wordSoFar){
String tempLetters = new String(guessedLetters);//converting char array to string to compare later in method
userLetter = readChar(" Enter your guess? ");//reads in the users string input and sets to variable temp
for(int k =0; k < 26; k++){//for loop for checking if letter guessed before
while(userLetter == tempLetters.charAt(k)){//while input is in tempLetters will ask for user guess
userLetter = readChar(" Enter your guess? ");//reads in the users char input
}
}
for(int l = 0; l< word.length(); l++){
if(word.charAt(l) == userLetter){//checking if the letter is in the word
wordSoFar[l] = userLetter;
System.out.println("Correct");
}
}//end for
for(int p =0 ; p<tempLetters.length(); p++){
if(userLetter == alphabet.charAt(p)){
guessedLetters[p] = userLetter;
}//end if
}//end for
if((userLetter != word.charAt(0)) && (userLetter != word.charAt(1)) && (userLetter != word.charAt(2)) &&
(userLetter != word.charAt(3)) && (userLetter != word.charAt(4)) && (userLetter != word.charAt(5))){
remainingGuesses--;
}
System.out.print("Letters guessed: ");//output guessed letters
System.out.println(guessedLetters);
System.out.print("Word so far: ");//output the word so far
System.out.println(wordSoFar);
System.out.println("Guesses left: " + remainingGuesses);//output the amount of guesses left
if((wordSoFar[0] == word.charAt(0)) && (wordSoFar[1] == word.charAt(1)) && (wordSoFar[2] == word.charAt(2)) &&
(wordSoFar[3] == word.charAt(3)) && (wordSoFar[4] == word.charAt(4)) && (wordSoFar[5] == word.charAt(5))){
System.out.println("-----------------------");
System.out.println("Well done you have won!");
System.out.println("-----------------------");
win = true;
}//end if
}//end userGuess
//--------------------------------------------------------------------------------------------------
// This method is used to get an integer input from the user and will be used in the gamesToBePlayed
// method to get the total amount of games that will be played .
//--------------------------------------------------------------------------------------------------
public static int readInt(String prompt){
System.out.println(prompt);
int userInput = 0;
try{
Scanner keyboard = new Scanner(System.in);
userInput = keyboard.nextInt();
}
catch(Exception e){
System.out.println("Not a number between 1 - 3");
}
return userInput;
}//end readInt
//--------------------------------------------------------------------------------------------------
// This method will be used to get a Char input from the user which will be used in the userGuess
// guess mehod for the letter that player is guessing.
//--------------------------------------------------------------------------------------------------
public static char readChar(String prompt){
char tempChar;
String tempString;
System.out.println(prompt);
Scanner keyboard = new Scanner(System.in);
tempString = keyboard.nextLine();
tempChar = tempString.charAt(0);
return tempChar;
}//end readChar
//--------------------------------------------------------------------------------------------------
// This method will be used to set the wordsofarto underscores and return it
//--------------------------------------------------------------------------------------------------
public static char[] setWordSoFar( char[] wordSoFar){
for(int i=0;i<wordSoFar.length;i++){//for loop to set all chars to underscores
wordSoFar[i] = '_';//set all chars to underscores
}//end for
return wordSoFar;
}
//--------------------------------------------------------------------------------------------------
// This method will be used to set huessedLetters to spaces and return it
//--------------------------------------------------------------------------------------------------
public static char[] setGuessedLetters(char[] guessedLetters){
for(int j = 0; j<26; j++){//create for loop to replace all chars in guessedLetters
guessedLetters[j] = ' ';//setting all chars in variable to spaces
}//end for
return guessedLetters;
}
}//end class
Re: Getting an error! String.charAt(Unknown Source) ???
Time to do some debugging to see what the code is doing. Try debugging your code by adding println() statements to show execution progress and how variable values are changing. For example:
Add a: System.out.println("var=" + var);
after every line where a variable is changed by an assignment statement or read into.