I'm just a beginner in coding and trying to make my 1st project with several classes that is a hangman game. I know there are a lot of threads on the topic here but couldn't manage to find a solution that would work with StringBuilder. I'm stuck with catching multiple letters in the word. Could anyone possibly help?
the method under question is checkAnswer and is below:
public void checkAnswer (){
if (logic.line.indexOf(answer)!= -1){
System.out.println ("You are right! The letter " + answer + " exists");
StringBuilder guessedChar = new StringBuilder(logic.newLine);
guessedChar.setCharAt(logic.line.indexOf(answer), answer);
lettersGuessed = answer +lettersGuessed;
score = score + 1;
System.out.println("Letters guessed: " + lettersGuessed);
System.out.println("Letters missed: " + lettersMissed);
System.out.println("Your score is:" + score);
logic.newLine = guessedChar.toString();
System.out.println(logic.newLine);
}}
Below is the full code:
main class
public class Main {
public static void main(String[] args) throws Exception {
Logic act = new Logic();
Game game = new Game();
act.getListOfMovies();
act.CodedLine();
do { game.input();
game.checkCondition();
game.checkAnswer();
game.checkScore();
} while (game.lettersGuessed.length() != act.line.length() && game.score!= -10);
}}
Class Logic
public class Logic {
static String line;
static String newLine;
public String[] listOfMovies;
public Scanner fileScanner;
public Logic() {
}
public String getListOfMovies() throws Exception {
File fileWithMovies = new File("MoviesList.txt");//file access
Scanner fileScanner = new Scanner(fileWithMovies);//file scan
while (fileScanner.hasNext()) { // while there is a next line
line = fileScanner.nextLine();
String[] listOfMovies = new String[24]; //introduce array
for (int i = 0; i < listOfMovies.length; i++) { //
listOfMovies[i] = fileScanner.nextLine();
}
int random = (int) (Math.random() * listOfMovies.length); //get random number
for (int i = 0; i < line.length(); i++) { //get random movie
if (Character.isLetter(line.charAt(i))) {
line = listOfMovies[random];
System.out.println(line);
}
return line;
}
return line;
}return line;
}
public String CodedLine() {
newLine = line.replaceAll("[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]", "_");
System.out.println(newLine);
return newLine;
}}
Class Game
public class Game {
char answer;
Logic logic = new Logic();
String lettersGuessed = " ";
String lettersMissed = " ";
int score = 0;
public char input () {
Scanner inputScanner = new Scanner(System.in);
System.out.println("Type in your guess");
answer = inputScanner.next().charAt(0);
System.out.println("Your guess: " + answer);
return answer;
}
public void checkCondition (){
if (logic.line.indexOf(answer)==-1){
System.out.println("You are wrong. The letter " + answer + " does not exist");
lettersMissed = answer + lettersMissed;
score = score - 1;
System.out.println("Letters guessed: " + lettersGuessed);
System.out.println("Letters missed: " + lettersMissed);
System.out.println("Your score is:" + score);
}}
public void checkAnswer (){
if (logic.line.indexOf(answer)!= -1){
System.out.println ("You are right! The letter " + answer + " exists");
StringBuilder guessedChar = new StringBuilder(logic.newLine);
guessedChar.setCharAt(logic.line.indexOf(answer), answer);
lettersGuessed = answer +lettersGuessed;
score = score + 1;
System.out.println("Letters guessed: " + lettersGuessed);
System.out.println("Letters missed: " + lettersMissed);
System.out.println("Your score is:" + score);
logic.newLine = guessedChar.toString();
System.out.println(logic.newLine);
}}
public void checkScore (){
if (score == -10) {
System.out.println("The game is over! You lost..."); }}}
//Create list for index
ArrayList<Integer>answerIndexList=new ArrayList<Integer>();
//get char index
for (int i=0;i<logic.line.length();i++){
if(logic.line.charAt(i) == answer){
answerIndexList.add(i);
}
}
//replace index with answer
for(int i=0;i<answerIndexList.size();i++){
guessedChar.setCharAt(answerIndexList.get(i), answer);
}
logic.newLine = guessedChar.toString();
Not gonna solve it for you, not what this site is for, but suggestions:
check this method - basically you tell it where the indexOf should start searching. At first you start with 0, then if you find a result you start at foundResultIndex + 1, put it all in a loop and voila.
word: batman, guess: a
int startAt = 0;
int foundResultIndex = "batman".indexOf('a', startAt) // 1
startAt = foundResultIndex + 1;
foundResultIndex = "batman".indexOf('a', startAt) // 4
...
don't keep so much state in your programs, especially static like in Logic class. Your getListOfMovies is perfect example, you are already returning a result, why keep it in some line variable? Use the returned result instead.
the replaceAll is funny, do this instead line.replaceAll("[a-z]", "_");
Related
My first class that creates the ArrayList and populates it with the Skill objects
import java.util.ArrayList;
public class Skill {
String skillName;
int skillValue;
public static ArrayList<Skill> skillList = new ArrayList<Skill>();
public Skill(String newSkillName, int newSkillValue){
setSkillName(newSkillName);
setSkillValue(newSkillValue);
}
public static void initializeSkillList(){
//Creating the Skill obj's
Skill str = new Skill("Str", 1);
Skill dex = new Skill("Dex", 1);
Skill intl = new Skill("Int", 1);
Skill con = new Skill("Con", 3);
//Adding them to the Skill ArrayList
skillList.add(str);
skillList.add(dex);
skillList.add(intl);
skillList.add(con);
//Debug statement to check if the values are correct
System.out.println(skillList.get(1).skillValue);
}
}
I am attempting to access the objects skillValue and skillName from the ArrayList in my Main.java class. I have setters and getters.
This is the Main class
import java.util.Scanner;
public class Main {
static Character playerCharacter;
static boolean charCreationComplete = false;
static boolean endGame = false;
static Scanner scnr = new Scanner(System.in);
public static void main(String[] args){
System.out.println("\n\nWelcome to Garterra!\n\n");
Archetype.initializeArchetypeList();
Skill.initializeSkillList();
if (!charCreationComplete){
charCreation(scnr);
charCreationComplete = true;
}
charCreation(scnr); then accesses the skillList through getters and setters
charCreation() Method:
private static void charCreation(Scanner scnr){
System.out.println("\nEnter player name:\n\n");
String newName = scnr.nextLine();
System.out.println("You Entered " + newName + " for your name!\n");
System.out.println("Next, Choose your Archetype: 0 = Ranger\n");
int archetypeIndex = scnr.nextInt();
Character.currArchetype = Archetype.archetypeList.get(archetypeIndex);
Character.archetypeName = Archetype.archetypeList.get(archetypeIndex).getArchetypeName();
System.out.println("You have chosen " + Character.archetypeName + ".\nThis gives you " + Character.currArchetype.totalSpendableSkillPoints + " total spendable skill points!\n");
System.out.println("Now, spend those skill points.\n");
if (Character.currArchetype.getArchetypeName().contains("Ranger")){
Ranger.dexModifierCalc(1);
Ranger.conModifierCalc(1);
}
while (Character.currArchetype.totalSpendableSkillPoints > 0){
System.out.println("How many points would you like to put into Strength?\nThis impacts your melee weapon damage and carry weight.\n");
int strAddPoints = scnr.nextInt();
Skill.skillList.get(0).setSkillValue(Skill.skillList.get(0).getSkillValue() + strAddPoints);
Character.currArchetype.setTotalSpendableSkillPoints(Character.currArchetype.totalSpendableSkillPoints - strAddPoints);
strAddPoints = 0;
System.out.println("You now have " + Skill.skillList.get(0).getSkillValue() + "\n");
if (Character.currArchetype.totalSpendableSkillPoints == 0){
break;
}
if (Character.currArchetype.totalSpendableSkillPoints > 0){
System.out.println("How many points would you like to put into Dexterity?\nThis impacts your ranged weapon damage.\n");
int dexAddPoints = scnr.nextInt();
Skill.skillList.get(1).setSkillValue(Skill.skillList.get(1).getSkillValue() + dexAddPoints);
Character.currArchetype.setTotalSpendableSkillPoints(Character.currArchetype.totalSpendableSkillPoints - dexAddPoints);
dexAddPoints = 0;
System.out.println("You now have " + Skill.skillList.get(1).getSkillValue() + "\n");
}
if (Character.currArchetype.totalSpendableSkillPoints == 0){
break;
}
if (Character.currArchetype.totalSpendableSkillPoints > 0){
System.out.println("How many points would you like to put into Intelligence?\nThis impacts your magic damage.\n");
int intAddPoints = scnr.nextInt();
Skill.skillList.get(2).setSkillValue(Skill.skillList.get(2).getSkillValue() + intAddPoints);
Character.currArchetype.setTotalSpendableSkillPoints(Character.currArchetype.totalSpendableSkillPoints - intAddPoints);
intAddPoints = 0;
System.out.println("You now have " + Skill.skillList.get(2).getSkillValue() + "\n");
}
if (Character.currArchetype.totalSpendableSkillPoints == 0){
break;
}
if (Character.currArchetype.totalSpendableSkillPoints > 0){
System.out.println("How many points would you like to put into Strength?\nThis impacts your melee weapon damage and carry weight.\n");
int conAddPoints = scnr.nextInt();
Skill.skillList.get(3).setSkillValue(Skill.skillList.get(3).getSkillValue() + conAddPoints);
Character.currArchetype.setTotalSpendableSkillPoints(Character.currArchetype.totalSpendableSkillPoints - conAddPoints);
conAddPoints = 0;
System.out.println("You now have " + Skill.skillList.get(3).getSkillValue() + "\n");
}
}
int newHealthPoints = Character.healthPointsCalc();
System.out.println("You have " + newHealthPoints + " health points!\n\n");
int newTotalCarryWeight = Character.carryWeightCalc(Character.currArchetype.getLevel());
System.out.println("Your total carry weight is " + newTotalCarryWeight + ".\n");
int newExperince = 0;
playerCharacter = new Character(newName, newHealthPoints, newExperince, 1, Archetype.archetypeList.get(archetypeIndex), newTotalCarryWeight);
}
If you create a getter for "skillList" then you can just say
Skill.getSkillList();
And then do whatever you want with this list.
To make your code a little better, change this
public static ArrayList<Skill> skillList = new ArrayList<>();
to this
public static List<Skill> skillList = new ArrayList<>();
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)
I have to make a quiz game for a project, and the program stops after line 12. Anybody know why? the code has comments in it to understand it, basically the program just stops, but doesn't close when it gets to the 12th line of code and I can't understand why. can any of you guys help with that? I'm pretty sure the rest of it is fine. Thanks. Also, the print statements that just print 1, or 2 were just checks to see where the program stopped, it didn't even get to the first one.
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
public class Quiz{
public static void main (String[] args) throws IOException{
Scanner keyboard = new Scanner(System.in);
QuizFile quizFile = new QuizFile();
quizFile.createQuestions();
System.out.println("hi");
System.out.println("1");
//opens the file
File file = new File("Questions.txt");
Scanner inputFile = new Scanner(file);
System.out.println("2");
String line;
//creates the ArrayList
ArrayList<String> listOfQuestions = new ArrayList<String>();
int lineCounter = 0;
//counts how many lines there are in the file
while(inputFile.hasNextLine()){
lineCounter++;
}
System.out.println("3");
//adds the quesitons in the file to the ArrayList by reading specific lines to the list
for (int lineIndex = 1; lineIndex <= lineCounter; lineIndex++){
if (lineIndex == 1){
line = inputFile.nextLine();
listOfQuestions.add(line);
}
if (lineIndex == 10){
line = inputFile.nextLine();
listOfQuestions.add(line);
}
if (lineIndex == 18){
line = inputFile.nextLine();
listOfQuestions.add(line);
}
if (lineIndex == 27){
line = inputFile.nextLine();
listOfQuestions.add(line);
}
if (lineIndex == 36){
line = inputFile.nextLine();
listOfQuestions.add(line);
}
else{
line = inputFile.nextLine();
}
}
System.out.println("4");
inputFile.close();
System.out.println("5");
inputFile = new Scanner(file);
System.out.println("Welcome to the Harry Potter Quiz! Good Luck!");
/*This is the setup for all of the questions, it works the same way for each question.
First, a question object is created, the question is read, and then displayed. Then
the answers are read, and displayed. Then the user answers the question, which is loggged
and the correct answer is retrieved from the file, as well as times tried and times correct.
When the user answers the question, a loop tests if it is a valid iput. If not, then the user
is asked again for a valid input until one is achieved.
*/
//Question 0
System.out.println("Question 0:");
Question question0 = new Question();
question0.getQuestion();
System.out.println(question0.question);
System.out.println("Answers:");
int question0NumberOfChoices = question0.getNumberOfChoices();
question0.getAnswers();
for(int j = 0; j < question0.numberOfChoices; j++){
System.out.println(j + ":" + question0.answers[j]);
}
int question0CorrectAnswer = question0.getCorrectAnswer();
int question0TimesTried = question0.getTimesTried();
int question0TimesCorrect = question0.getTimesCorrect();
int question0Answer;
do {
question0Answer = keyboard.nextInt();
} while (question0Answer > (question0.numberOfChoices - 1) && question0Answer < 0);
//Question 1
System.out.println("Question 1:");
Question question1 = new Question();
question1.getQuestion();
System.out.println(question1.question);
System.out.println("Answers:");
int question1NumberOfChoices = question1.getNumberOfChoices();
question1.getAnswers();
for(int j = 0; j < question1.numberOfChoices; j++){
System.out.println(j + ":" + question1.answers[j]);
}
int question1CorrectAnswer = question1.getCorrectAnswer();
int question1TimesTried = question1.getTimesTried();
int question1TimesCorrect = question1.getTimesCorrect();
int question1Answer;
do {
question1Answer = keyboard.nextInt();
} while (question1Answer > (question1.numberOfChoices - 1) && question1Answer < 0);
//Question2
System.out.println("Question 2:");
Question question2 = new Question();
question2.getQuestion();
System.out.println(question2.question);
System.out.println("Answers:");
int question2NumberOfChoices = question2.getNumberOfChoices();
question2.getAnswers();
for(int j = 0; j < question2.numberOfChoices; j++){
System.out.println(j + ":" + question2.answers[j]);
}
int question2CorrectAnswer = question2.getCorrectAnswer();
int question2TimesTried = question2.getTimesTried();
int question2TimesCorrect = question2.getTimesCorrect();
int question2Answer;
do {
question2Answer = keyboard.nextInt();
} while (question2Answer > (question2.numberOfChoices - 1) && question2Answer < 0);
//Question 3
System.out.println("Question 3:");
Question question3 = new Question();
question3.getQuestion();
System.out.println(question3.question);
System.out.println("Answers:");
int question3NumberOfChoices = question3.getNumberOfChoices();
question3.getAnswers();
for(int j = 0; j < question3.numberOfChoices; j++){
System.out.println(j + ":" + question3.answers[j]);
}
int question3CorrectAnswer = question3.getCorrectAnswer();
int question3TimesTried = question3.getTimesTried();
int question3TimesCorrect = question3.getTimesCorrect();
int question3Answer;
do {
question3Answer = keyboard.nextInt();
} while (question3Answer > (question3.numberOfChoices - 1) && question3Answer < 0);
//Question 4
System.out.println("Question 4:");
Question question4 = new Question();
question4.getQuestion();
System.out.println(question4.question);
System.out.println("Answers:");
int question4NumberOfChoices = question4.getNumberOfChoices();
question4.getAnswers();
for(int j = 0; j < question4.numberOfChoices; j++){
System.out.println(j + ":" + question4.answers[j]);
}
int question4CorrectAnswer = question4.getCorrectAnswer();
int question4TimesTried = question4.getTimesTried();
int question4TimesCorrect = question4.getTimesCorrect();
int question4Answer;
do {
question4Answer = keyboard.nextInt();
} while (question4Answer > (question4.numberOfChoices - 1) && question4Answer < 0);
//end of quesitons
//results
System.out.println("-------------------------------------");
System.out.println("Let's see how you did!");
int numberOfCorrectAnswers = 0;
int numberofQuestions = listOfQuestions.size();
/*For this part, there are 5 pieces that are the same. For each question, the program
prints the question, the correct answer, and the answer the user chose. Then it checks if the user
got it right, if so, it tells them, and if not, it also tells them. Then the program displays the
times the user got it right, and the percentage of how many times they got it right
*/
System.out.println(listOfQuestions.get(0));
System.out.println("The correct answer is: " + question0CorrectAnswer);
System.out.println("Your answer was: " + question0Answer);
if(question0Answer == question0CorrectAnswer){
System.out.println("You got it right!");
numberOfCorrectAnswers++;
}
else{
System.out.println("Sorry, you got it wrong.");
}
System.out.println("Amount of times you got it correct: " + question0TimesCorrect);
System.out.println("Amount of tiems you tried it: " + question0TimesTried);
float question0Percentage;
if (question0TimesTried == 0){
question0Percentage = 0;
}
else{
question0Percentage = question0TimesCorrect / question0TimesTried;
} System.out.println("Percentage right: " + question0Percentage);
System.out.println(listOfQuestions.get(1));
System.out.println("The correct answer is: " + question1CorrectAnswer);
System.out.println("Your answer was: " + question1Answer);
if(question1Answer == question1CorrectAnswer){
System.out.println("You got it right!");
numberOfCorrectAnswers++;
}
else{
System.out.println("Sorry, you got it wrong.");
}
System.out.println("Amount of times you got it correct: " + question1TimesCorrect);
System.out.println("Amount of tiems you tried it: " + question1TimesTried);
float question1Percentage;
if (question1TimesTried == 0){
question1Percentage = 0;
}
else{
question1Percentage = question1TimesCorrect / question1TimesTried;
}
System.out.println("Percentage right: " + question1Percentage);
System.out.println(listOfQuestions.get(2));
System.out.println("The correct answer is: " + question2CorrectAnswer);
System.out.println("Your answer was: " + question2Answer);
if(question2Answer == question2CorrectAnswer){
System.out.println("You got it right!");
numberOfCorrectAnswers++;
}
else{
System.out.println("Sorry, you got it wrong.");
}
System.out.println("Amount of times you got it correct: " + question2TimesCorrect);
System.out.println("Amount of tiems you tried it: " + question2TimesTried);
float question2Percentage;
if (question2TimesTried == 0){
question2Percentage = 0;
}
else{
question2Percentage = question2TimesCorrect / question2TimesTried;
} System.out.println("Percentage right: " + question2Percentage);
System.out.println(listOfQuestions.get(3));
System.out.println("The correct answer is: " + question3CorrectAnswer);
System.out.println("Your answer was: " + question3Answer);
if(question3Answer == question3CorrectAnswer){
System.out.println("You got it right!");
numberOfCorrectAnswers++;
}
else{
System.out.println("Sorry, you got it wrong.");
}
System.out.println("Amount of times you got it correct: " + question3TimesCorrect);
System.out.println("Amount of tiems you tried it: " + question3TimesTried);
float question3Percentage;
if (question3TimesTried == 0){
question3Percentage = 0;
}
else{
question3Percentage = question3TimesCorrect / question3TimesTried;
} System.out.println("Percentage right: " + question3Percentage);
System.out.println(listOfQuestions.get(4));
System.out.println("The correct answer is: " + question4CorrectAnswer);
System.out.println("Your answer was: " + question4Answer);
if(question4Answer == question4CorrectAnswer){
System.out.println("You got it right!");
numberOfCorrectAnswers++;
}
else{
System.out.println("Sorry, you got it wrong.");
}
System.out.println("Amount of times you got it correct: " + question4TimesCorrect);
System.out.println("Amount of tiems you tried it: " + question4TimesTried);
float question4Percentage;
if (question4TimesTried == 0){
question4Percentage = 0;
}
else{
question4Percentage = question4TimesCorrect / question4TimesTried;
} System.out.println("Percentage right: " + question4Percentage);
/*This puts the percentages of correct questions into an array,
and then finds the highest and lowest one, and then displays both to the user
*/
float[] percentages = new float[5];
percentages[0] = question0Percentage;
percentages[1] = question1Percentage;
percentages[2] = question2Percentage;
percentages[3] = question3Percentage;
percentages[4] = question4Percentage;
float bestQuestion = percentages[0];
for (int index = 1; index < percentages.length; index++){
if(percentages[index] > bestQuestion){
bestQuestion = percentages[index];
}
}
float worstQuestion = percentages[0];
for (int index = 1; index < percentages.length; index++){
if(percentages[index] < worstQuestion){
worstQuestion = percentages[index];
}
}
System.out.println("Your worst percentage correct of a question was: " + worstQuestion);
System.out.println("Your best percentage correct of a question was: " + bestQuestion);
}
}
import java.io.*;
import java.util.Scanner;
public class Question{
public String question;
public int numberOfChoices;
public int answerChoice;
public int timesTried;
public int timesCorrect;
public String[] answers;
public String getQuestion() throws IOException{
Scanner keyboard = new Scanner(System.in);
File file = new File("Questions.txt");
Scanner inputFile = new Scanner(file);
question = inputFile.nextLine();
return question;
}
public int getNumberOfChoices() throws IOException{
File file = new File("Questions.txt");
Scanner inputFile = new Scanner(file);
numberOfChoices = inputFile.nextInt();
return numberOfChoices;
}
public String[] getAnswers() throws IOException{
File file = new File("Questions.txt");
Scanner inputFile = new Scanner(file);
String[] answers = new String[numberOfChoices];
for(int index = 0; index < numberOfChoices; index++){
answers[index] = inputFile.nextLine();
}
return answers;
}
public int getCorrectAnswer() throws IOException{
File file = new File("Questions.txt");
Scanner inputFile = new Scanner(file);
answerChoice = inputFile.nextInt();
return answerChoice;
}
public int getTimesTried() throws IOException{
File file = new File("Questions.txt");
Scanner inputFile = new Scanner(file);
timesTried = inputFile.nextInt();
return timesTried;
}
public int getTimesCorrect() throws IOException{
File file = new File("Questions.txt");
Scanner inputFile = new Scanner(file);
timesCorrect = inputFile.nextInt();
return timesCorrect;
}
}
import java.io.*;
public class QuizFile{
public static void main (String[] args){
}
public void createQuestions() throws IOException{
PrintWriter outputFile = new PrintWriter("Questions.txt");
outputFile.println("What is the only antidote to basilisk venom?");
outputFile.println("4");
outputFile.println("Phoenix Tears");
outputFile.println("Dragon's Blood");
outputFile.println("A Bezoar");
outputFile.println("Mandrake Draught");
outputFile.println("0");
outputFile.println("0");
outputFile.println("0");
outputFile.println("How many times was Nearly Headless Nick hit in the head with a blunt axe?");
outputFile.println("3");
outputFile.println("34");
outputFile.println("45");
outputFile.println("20");
outputFile.println("1");
outputFile.println("0");
outputFile.println("0");
outputFile.println("What magical object causes people to turn orange or sprout tentacle-like warts?");
outputFile.println("4");
outputFile.println("Metamorph-Medals");
outputFile.println("Decoy Detonators");
outputFile.println("The Mirror Of Erised");
outputFile.println("U-No-Poo");
outputFile.println("0");
outputFile.println("0");
outputFile.println("0");
outputFile.println("How does Felix Felicis behave when in the cauldron?");
outputFile.println("4");
outputFile.println("It Spills Over The Sides");
outputFile.println("It Bubbles Merrily");
outputFile.println("Droplets Leap Out Like Goldfish Above The Surface");
outputFile.println("Droplets Whizz Through The Air At High Speeds");
outputFile.println("2");
outputFile.println("0");
outputFile.println("0");
outputFile.println("How mamy brothers does Ron have?");
outputFile.println("3");
outputFile.println("3");
outputFile.println("7");
outputFile.println("5");
outputFile.println("2");
outputFile.println("0");
outputFile.println("0");
outputFile.close();
}
}
I am writing a code where a player gets to play hangman with a random word chosen from a text file. I keep getting this null pointer exception error, and I am not sure why. Sometimes when I run the program, I have no problems. But sometimes when I run, the program immediately crashes given me the null pointer exception error. Can anyone help me figure out why? Here is my code:
--Edit--
Error occurs in displayGallows method, when trying to set the variable puzzle.
import java.util.Scanner;
import java.util.Random;
import java.io.*;
public class Hangman {
private Scanner in = new Scanner(System.in);
private boardPiece[] board = {new boardPiece(0),new boardPiece(0),new boardPiece(3),
new boardPiece(1),new boardPiece(2),new boardPiece(0)};
private String puzzle;
private String puzzleWord;
private int puzzleIndex;
private Random generator = new Random(System.currentTimeMillis());
private boolean win;
private boolean over;
private String correct = "";
//private String guesses = "";
private char guesses[] = new char[26];
private int guessed;
private int misses;
private String puzzles[] = new String[5];
// = {"hello world","java is cool","athena is smelly","zach is awesome","athena is cool"};
public static void main(String [] args){
String letter;
String again = "y";
Hangman game = new Hangman();
try{
BufferedReader in =
new BufferedReader(new FileReader("puzzles.txt"));
int count = 0;
while (in.ready()) { //while there is another line in the input file
game.puzzles[count] = in.readLine(); //get line of data
count++; //Increment CWID counter
}
in.close();
}
catch(IOException e){
System.out.println("Error during reading/writing");
}
/*for(int x=0;x<game.puzzles.length;x++)
System.out.println("PUZZLE " + x + ": " + game.puzzles[x]);*/
System.out.println("Welcome to HangMan!");
System.out.println("To play, guess a letter to try to guess the word.");
System.out.println("Every time you choose an incorrect letter another");
System.out.println("body part appears on the gallows. If you guess the");
System.out.println("word before you're hung, you win");
System.out.println("If you get hung, you lose");
System.out.println("Time to guess...");
while(again.charAt(0) == 'y'){
game.displayGallows();
while(!game.over){
game.printBoard();
//System.out.println("Guessed: " + game.guesses);
game.printLettersGuessed();
System.out.println("The word so far: " + game.puzzle);
System.out.println("Choose a letter: ");
letter = game.in.next();
//game.guesses = game.guesses + " " + letter.charAt(0);
game.guesses[game.guessed] = letter.charAt(0);
game.guessed++;
game.sort();
if(game.puzzleWord.indexOf(letter.charAt(0)) != -1){
game.correct = game.correct + letter.charAt(0);
game.puzzle = game.puzzleWord.replaceAll("[^"+game.correct+" ]","-");
if(game.puzzleWord.replaceAll("["+game.correct+" ]","").length() == 0){
game.win = true;
game.over = true;
}
}
else
game.PrintWrongGuesses();
}
game.printBoard();
System.out.println("Solution: " + game.puzzleWord);
if(game.win)
System.out.println("Congratulations! You've solved the puzzle!");
else
System.out.println("You failed, failer!");
System.out.println();
System.out.println("Congratulations, you win!");
System.out.println("Do you want to play again? (y/n)");
again = game.in.next();
}
System.out.println("Goodbye!");
}
public void displayGallows(){
win = false;
over = false;
board[0].piece = " ______ ";
board[1].piece = " | | ";
board[2].piece = " | ";
board[3].piece = " | ";
board[4].piece = " | ";
board[5].piece = " _______| ";
puzzleIndex = generator.nextInt(puzzles.length);
puzzleWord = puzzles[puzzleIndex];
puzzle = puzzleWord.replaceAll("[A-Za-z]","-");
correct = "";
//guesses = "";
for(int x=0;x<26;x++)
guesses[x] = '~';
guessed = 0;
misses = 0;
}
public void printBoard(){
for(int x =0;x<6;x++)
System.out.println(board[x].piece);
}
public void PrintWrongGuesses(){
misses++;
System.out.println();
if(misses == 1){
board[2].piece = " 0 | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 2){
board[2].piece = " \\0 | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 3){
board[2].piece = " \\0/ | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 4){
board[3].piece = " | | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 5){
board[4].piece = " / | ";
System.out.println("Number of misses: " + misses);
}
else if(misses == 6){
board[4].piece = " / \\ | ";
System.out.println("Number of misses: " + misses);
over = true;
}
}
public void printLettersGuessed(){
System.out.print("Letters guessed already: ");
for(int x=0;x<26;x++){
if(guesses[x] != '~')
System.out.print(guesses[x] + " ");
}
System.out.println();
}
public void sort(){
boolean doMore = true;
while (doMore) {
doMore = false; // assume this is last pass over array
for (int i=0; i<guesses.length-1; i++) {
if (guesses[i] > guesses[i+1]) {
char temp = guesses[i];
guesses[i] = guesses[i+1];
guesses[i+1] = temp;
doMore = true; // after an exchange, must look again
}
}
}
}
class boardPiece{
public String piece;
public int total;
public int used;
boardPiece(int x){
used = 0;
total = x;
}
}
}
Thank you
Do your puzzles.txt have more than 5 lines? because you declared a private String puzzles[] = new String[5]; the problems seems to happen when puzzleWord = puzzles[puzzleIndex]; is trying to put a null into puzzleWord.
say your puzzle have:
aaaa
bbbb
cccc
when you declare ur puzzles[]= new String[5];
your puzzles memory goes like:
null
null
null
null
null
After that you populate the puzzles array:
aaaa
bbbb
cccc
null
null
when the randomed index is 3 or 4, NPE occurs.
can you check on which line null pointer exception occurs. Mostly it will occur when object is not initialized and your trying to do operation. So make sure object is initialized before using it.
Okay, here's the EDIT. After debugging it for a while I found that puzzles array is not being set properly when you read "puzzles.txt" file. Something funky is going on here in this piece of code. Make sure the file is read correctly and puzzles array gets what is intends to.
Hopefully, it's a good starting point for you.
try{
BufferedReader in =
new BufferedReader(new FileReader("puzzles.txt"));
int count = 0;
while (in.ready()) { //while there is another line in the input file
game.puzzles[count] = in.readLine(); //get line of data
count++; //Increment CWID counter
}
in.close();
}
catch(IOException e){
System.out.println("Error during reading/writing");
}
Why don't you try to debug it and see the values on puzzles and puzzleWord inside the method. That's the best way possible to see what's really going in.
Please check the path of your file puzzles.txt. It seems the file path is not correct. You must be getting an exception printed "Error during reading/writing". Handle it properly, if you are not able to read the file then don't proceed ahead.
Move the puzzles.txt file to correct path or provide a exact file path.
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());