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.
Related
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]", "_");
I am working on a rock paper scissors homework assignment for my java class. I am done with the program and I compiled it successfully. I ran the file and it looked like it was working. It gives me the menu and I choose a variable, R for example, and when I press enter it doesn't do anything but go to the next line. I press enter again and it gives me an index out of bounds error which I assume is because the second time it didn't have a variable to use. How do I get the program to move forward? The program is supposed to play five times then return a winner. Thanks in advance.This image is what I get when I run the program and press enter twice
package Rock;
import java.util.Scanner;
public class RPSG {
public static void main(String[] args) {
String[] computerHandArray = {"R","P","S"};
String computerHand ="", thisWinner="", theFinalWinner="";
int index=0;
int timesIWon=0;
int timesComputerWon=0;
Scanner in = new Scanner(System.in);
System.out.println("\tMenu\n\n(R) Rock\n(P) Paper\n(S) Scissors" + "\n\nEnter Your Hand (R, P, or S): ");
for (int i=0; i<5; i++) {
String myHandString = in.nextLine();
String myHand = myHandString.substring(0,1);
myHand = myHand.toUpperCase();
index = (int)(Math.random() * 10) % 3;
computerHand = computerHandArray[index];
thisWinner = theWinnerofOneGame(myHand, computerHand);
if(thisWinner.equals("ME")){
timesIWon++;
}
else if(thisWinner.equals("COMPUTER")) {
timesComputerWon++;
}
}
if(timesIWon == timesComputerWon)
theFinalWinner = "TIE";
else if(timesIWon > timesComputerWon)
theFinalWinner = "ME";
else if(timesComputerWon > timesIWon)
theFinalWinner = "COMPUTER";
System.out.println("I won :" + timesIWon);
System.out.println("I won :" + timesComputerWon);
System.out.println("The Final Winner after 5 games is:" +theFinalWinner);
}
private static String theWinnerofOneGame(String myHand, String computerHand){
String theWinner = "Tie";
if(myHand.equals(computerHand)) {
theWinner = "Tie";
}
else if(myHand.equals("R")) {
if (computerHand.equals("P")) {
theWinner = "COMPUTER";
}
}
else if(computerHand.equals("S")) {
theWinner = "ME";
}
else if(myHand.equals("P")) {
if (computerHand.equals("R")) {
theWinner = "ME";
}
else if(computerHand.equals("S")) {
theWinner = "COMPUTER";
}
}
else if(myHand.equals("S")) {
if (computerHand.equals("R")) {
theWinner = "COMPUTER";
}
else if(computerHand.equals("P")) {
theWinner = "ME";
}
}
return theWinner;
}
}
You print the prompt for input only once, i.e. before the for loop. Now when you enter your first input, the content of the loop will be executed. Because you don't print anything inside the loop, there is no prompt for the next round. After you press enter a second time, the in.nextLine() returns an empty string and subsequently, the substring method throws the exception.
You should probably do something like this (note the marked lines):
System.out.println("\tMenu\n\n(R) Rock\n(P) Paper\n(S) Scissors" + "\n\n");
for (int i=0; i<5; i++) {
> System.out.println("Enter Your Hand (R, P, or S): ");
String myHandString = in.nextLine();
String myHand = myHandString.substring(0,1);
myHand = myHand.toUpperCase();
index = (int)(Math.random() * 10) % 3;
computerHand = computerHandArray[index];
thisWinner = theWinnerofOneGame(myHand, computerHand);
if(thisWinner.equals("ME")){
timesIWon++;
> System.out.println("You won.");
} else if(thisWinner.equals("COMPUTER")) {
timesComputerWon++;
> System.out.println("The computer won.");
}
}
And even better, check if the input of the user is valid before computing the substring.
I am beginner in java. I was trying to emulate the single dimension array battle ship code from heads first java book. The code is not failing, but I am not able to make it work properly.
Example: [1,2,3] is the array which contains the location of the battle ship. If I guess any number except 1, it is displaying as miss. But if I guess it as 1 three times (length of battleship) in a row I am making it as kill. I am not able to figure out this issue.
Could you please help me out here. The code is posted below:
package battleship;
public class battleship {
public int[] battleship = new int[3];
public int numofhits = 0;
String result = "miss";//instance variables complete
//setter method to initialize the array which holds the battle ship location
public void setbattleshiploc(int startpos) {
int i = 0;
for(i = 0; i < battleship.length; i++) {
battleship[i] = startpos + i;
System.out.println(battleship[i]);
}
System.out.println("initialized array is: " + java.util.Arrays.toString(battleship));
}
//getter method to print the set battleship array
public int[] getbattleshiploc() {
System.out.println("Battleship array is: " + battleship);
return battleship;
}
//checking whether user guess inside the battleship array location
public String guessloc(int guessnum) {
//int i = 0;
for(int cell : battleship) {
System.out.println("Guessed number is: " + guessnum + " array element: " + battleship[cell]);
System.out.println("cell: "+ cell + " ,battleship[cell]: " + battleship[cell] );
if(cell == guessnum) {
numofhits++;
if(numofhits == 3) {
result = "kill";
return result;
}//if the hits are 3 then return kill indicating that no more battle ship is available
else {
result = "hit";
return result;
}//end inner else
}//end outer if
else {
//numofhits++;
result = "miss";
return result;
}//end the if-else
}//end for loop
return "finished";
}//end function guessloc
}//end class
package battleship;
import java.util.Scanner;
public class gamelauncher {
public Scanner[] reader;
public static void main(String[] args) {
String result = "miss";
int numofguess = 0;
//int loopnum = 0;
battleship launchgame = new battleship();//launch the game
int startpos = (int) (Math.random() * 5);//generate random number between 0-4
//int[] location = {startpos, startpos + 1, startpos + 2};//initialize three consecutive array element
launchgame.setbattleshiploc(startpos);//set the array as the battleship location using setter
//display the battleship position
System.out.println("Battle shipt positions are: " + startpos +" ," + startpos+1 + " ," + startpos+2);
System.out.println("the battle ship array is: " + launchgame.getbattleshiploc());
//int[] battleshiplocation = launchgame.getbattleshiploc();
System.out.println(java.util.Arrays.toString(launchgame.getbattleshiploc()));
while(result != "kill") {
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("Enter a number: ");
int guess = reader.nextInt(); //get the user input integer
//reader.close();//close the scanner
//loopnum++;
numofguess++;
if(guess < 0 || guess > 7) {
System.out.println("Maximum space available is 7 units(0-6) and battleship length is 3 units, Please provide the location accordingly");
continue;
}//close if loop and go to the loop execution if the guess is not within the limits
else {
result = launchgame.guessloc(guess);
System.out.println("response from guessing method: " + result);
//get the status(hit/miss/kill) back from guess location method
if(result == "kill") {
System.out.println("We have destroyed all the parts of battle ship and it took " + numofguess +" guesses" );
break;//get out of the loop as we have destroyed everything
}//end kill
else if(result == "hit") {
System.out.println("You have destroyed " + launchgame.numofhits+" parts of batlleship, please continue");
continue;
}
else {
System.out.println("It's a miss dumbo, try again");
continue;
}
}//end outer else statement
}//end while loop
}//end main method
}//end class
I can help you by giving you this function a bit changed. Please try to fix the rest of your code on your own. It will give you important experience.
public String guessloc(int guessnum) {
for(int i=0;i<battleship.length;++i) {
if(battleship[i] == guessnum) { //it's a hit
battleship[i] = -1; //you cant hit it again, so change it
if(++numofhits == 3) {
return "kill";
}else
return "hit";
}
}
return "miss"; //miss should be outside of the for loop
}
I believe the problem is that when you are comparing Strings u are using == instead of .equals() so your code should like like this:
if(result.equals("kill"))
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("-");
}
}
}
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.