Score Calculation In Hang Man:Java code - java

I am writing a code for Hang Man game in Java.But I cannot write a proper code or find a way to calculate users' score and printing it at the users' end command with 0:stop.Here are the score calculation rules;
Score is computed as number of letters of the word minus number of letters currently displayed.
Here “table “ score is 5-4=1 as when the user make a guess there are 4 letters already displayed.
If the user guess is not correct score is 0
If the man’s figure is completed before a guess, the score is 0
Each play of the game bu the same user is a session, the same word cannot be held by computer.
If “table” is held as a “things” it can bot be held by computer again n the same session.
When the user press 0 in the main mene, the session ends.
Toptal number of plays, how many times correctly guessed , and total score of the user is displaid to the screen.
Also,i have a problem to prevent duplicate in random selected words array
import java.util.Random;
import java.util.Scanner;
public class CEVIK_CAGATAY{
public static char[] star;
public static void main (String args[])
{
char game[];
int category;
int correct=0;
Scanner input = new Scanner(System.in);
Random r = new Random();
int totalplay=0;
int totalscore=0;
String man[] = new String[7];
man[2] = " --\n o |\n/ |\n |\n_____\n";
man[3] = " --\n o |\n/| |\n |\n_____\n";
man[4] = " --\n o |\n/|\\|\n |\n_____\n";
man[5] = " --\n o |\n/|\\|\n/ |\n_____\n";
man[6] = " --\n o |\n/|\\|\n/ \\|\n_____\n";
String arr[]={"serhat","cagatay","begum","emre","berk","ali","veli","istanbul",
"ankara","mersin","izmir","antalya","new york","samsun","kedi","kopek",
"kus","ayi","bocek","karinca","manda","masa","pencil","bag","clock","televison","book","glass"};
int arr1 []={6,7 };
System.out.println("0 To Stop,1 to Continue");
category=input.nextInt();
while(category!=0){
System.out.println("0 To STop,1 to Continue");
String word = arr[r.nextInt(arr.length)];
for(int i=0; i<arr.length;i++) {
if(arr[i]==word){
int letterlength=arr1[i];
}
//letterlength-existedlength=guessremain;
}
int count = word.length();
char[] CharArr=word.toCharArray();
char[] star = word.toCharArray();
for(int i=0;i<star.length;i++)
{
star[i] = '*';
System.out.print(star[i]);
}
for (int i=1; i<=5; i++)
{
System.out.printf ("\nGuess a Letter:");
char letter= input.next().charAt(0);
for (int j=0;j<CharArr.length; j++)
{
if(letter == star[j])
{
System.out.println("this word already exist");
}
else
{
if(letter==CharArr[j])
{
star[j]=letter;
i--;
System.out.printf("CORRECT GUESS!\n");
correct++;
}
}
}
System.out.print(star);
switch(i+0)
{
case 1: System.err.printf("Strike 1\n");
System.out.println(man[2]);
break;
case 2: System.err.printf("Strike 2\n");
System.out.println(man[3]);
break;
case 3: System.err.printf("Strike 3\n");
System.out.println(man[4]);
break;
case 4: System.err.printf("Strike 4\n");
System.out.println(man[5]);
break;
case 5: System.err.printf("Strike5\n");
System.err.printf("You're out!!! The word is Not_Matched\n");
System.out.println(man[6]);
break;
}
System.out.printf("\n");
if((new String(word)).equals(new String(star)))
{
System.err.printf("Winner Winner\n");
break;
}
}
totalplay++;
totalscore+=correct;
System.out.println("CONTINUE 1,STOP 0");
category=input.nextInt();
if(category==0) {
System.out.println(totalplay);
System.out.println(totalscore);
}
}
}
}

Get rid of the following for loop. It serves no purpose except to throw an Array Index Out of Bounds error. Your program runs without it. Be sure to practice best practices for language as well (such as camelCase for naming variables). It makes your code easier for humans to understand.
for(int i=0; i<arr.length;i++) {
if(arr[i]==word){
int letterlength=arr1[i];
}
//letterlength-existedlength=guessremain;
}

Related

How to create random.txt file then randomly 500 random integers in the file then use that file to run common algorithms on them?

The code given below is not working:
My tasks are to,
Write a program that generates 500 Random Integers and stores them into an array. Integer values will be between 1 - 1000.
Print the 500 Random Integers to .txt file
The main method will control the run of the program. (menu, etc.)
Create a menu using the if/else ladder or switch case to control the operation of the program. The menu should be in main.
Create a “programmer created class” called Common_Algo
Read the 500 Random Integers from th .txt file you created in Task
2:
Use the class constructor to fill the array with random integers from the .txt file. The 500 integer array (arr[500]) will be an instance variable in the “programmer created class” - Common_Algo
All methods below will be encapsulated together with the 500 integer array in the Common_Algo class.
The main method from outside the Common_Algo class will control the
operation of the program.
Implement methods to achieve each outcome given below.
(Your menu will call the methods. All methods will operate on the same Array.)
Enter 1. Output all values
Enter 2. Output Sum of All Values and the Mean Average of Values
Enter 3. Output all odd numbers
Enter 4. Output all even numbers\
Enter 5. Output Middle Values (Values in the Middle)
Enter 6. Output First Value in the Array
Enter 7. Output Last Value in the Array
Enter 8. Enter a Search Value
Enter 9. Output Sorted Array
Enter 10. Output the Highest Value and its location in the array.
Enter 11: Output Lowest Value and its location in the array.
Enter 12: Exit
**Following is what I have implemented so far but it does not compile on the command prompt.**
import java.io.*;
import java.util.*;
public class Common_Algo
{
private int i;
int [] arr;
public Common_Algo()
{
try {
FileReader file = new FileReader("random.txt");
Scanner scanner = new Scanner(file);
arr = new int [500];
i = 0;
while (scanner.hasNextInt())
{
arr[i++] = scanner.nextInt();
}
}
catch (Exception e)
{
System.out.println(e);
}
}
void printAllValues()
{
for (i = 0; i<500; i++)
{
System.out.println(arr[i]);
}
}
void sumAndMean()
{
// calculate the sum
int sum = 0;
float average = 0;
for (int i = 0; i< arr.length; i++){
sum = sum + arr[i];
}
System.out.println("The sum of all the elements in the array " + sum);
// calculate the average
average = sum/arr.length;
System.out.println("Average of all vlaues of an array:" + average);
}
void oddNumber()
{
System.out.println("Odd numbers in array is:");
for(int i = 0; i<arr.length; i++)
{
if (arr[i]%2 ==0)
{
System.out.println(arr[i]);
}
}
}
void evenNumber()
{
System.out.println("Even numbers in array is:");
for(int i=0; i<arr.length; i++)
{
if (arr[i]%2==0)
{
System.out.println(arr[i]);
}
}
}
void middleValue(){
int m = 0;
if (arr.length%2 == 1)
{
m=(arr[(arr.length + 1)/2-1]);
}
else
{
m=(arr[arr.length/2-1]+arr[arr.length/2])/2;
}
System.out.println("Middle Value = "+ m);
}
void firstValue(){
System.out.println("The first value in the array is: " + arr[0]);
}
void lastValue()
{
System.out.println("The last value in the array is: " +arr[arr.length-1]);
}
void searchValue()
{
Scanner scanner = new Scanner (System.in);
int search_Value,flag=0;
System.out.println("Enter search value: ");
search_Value = scanner.nextInt();
//this does linear search for searching the value in array
for (int i = 0; i<arr.length; i++)
{
if (search_Value == arr[i])
{
System.out.println("Value " + search_Value +" is found at location "+ i);
flag = 1;
}
}
if (flag == 0)
{
System.out.println("Value " + search_Value + " is not found inside the array");
}
}
void sortArray()
{
Arrays.sort(arr);
System.out.println("The sort array list: ");
//sort array list
for (i=0; i<arr.length; i++){
System.out.println(arr[i]);
}
}
void highValue()
{
int max = arr [0];
for (int i = 1; i < arr.length; i++){
if (arr[i] > max){
max = arr[i];
System.out.println("The highest value of array is: " + max);
}
}
}
void lowValue()
{
int min = arr[0];
for (int i = 1; i <arr.length; i++)
if (arr[i] < min)
min = arr[i];
System.out.println("The lowest value in the array: " + min);
}
}
class RandomData
{
public static void main(String[] args) {
int i,choice;
Scanner scanner = new Scanner(System.in);
Random rnum = new Random();
try {
PrintWriter fileout = new PrintWriter(new FileWriter ("random.txt"));
for (i = 0; i<500; i++)
{
fileout.println(rnum.nextInt(1000));
}
fileout.close();
}
catch (Exception e)
{
System.out.println(e);
}
Common_Algo object = new Common_Algo();
do
{
System.out.println("Enter 1 for: Output of all values ");
System.out.println("Enter 2 for: Ouput of Sum and mean Average values");
System.out.println("Enter 3 for: Output of all odd numbers");
System.out.println("Enter 4 for: Output of all even numbers" );
System.out.println("Enter 5 for: Output of middle values");
System.out.println("Enter 6 for: Output of first value in the array");
System.out.println("Enter 7 for: Output of last vlaue in the array");
System.out.println("Enter 8 for: Output of the entered search value");
System.out.println("Enter 9 for: Output of the Sorted Array");
System.out.println("Enter 10 for: Output of the highest value and its location in the array");
System.out.println("Enter 11 for: Output of lowest value and its location in the array");
System.out.println("Enter 12 for: Exit");
System.out.println("Please enter your choice");
choice = scanner.nextInt();
switch(choice)
{
case 1:
object.printAllValues();
break;
case 2:
object.sumAndMean();
break;
case 3:
object.oddNumber();
break;
case 4:
object.evenNumber();
break;
case 5:
object.middleValue();
break;
case 6:
object.firstValue();
break;
case 7:
object.lastValue();
break;
case 8:
object.searchValue();
break;
case 9:
object.sortArray();
break;
case 10:
object.highValue();
break;
case 11:
object.lowValue();
break;
case 12:
System.exit(0);
}
}
while(choice!=12);
}
}
Do not try to do everything at once in one big jump. Do it step by step. Your instructor has kindly already broken the problem up into steps. Write code for each step separately. Test that code to make sure it works, fixing any errors you find. Yes, this does mean reading and understanding any compile errors you find. Because you are only writing one piece at a time, there should not be too many errors in each piece.
When you have a tested and working piece of code, integrate it with the other pieces you have written so far and test the new combined code. Again, fix all errors.
This stepwise approach means you never have a big blob of code to fix, just small pieces which are a lot easier to work with. You build your final program piece by piece, testing and fixing all the way.

Implementing a second ship into one dimensional battleship game Java

I have designed the battleship game to only have one ship hidden and now I have to implement another ship into the game. I am new to Java and was wondering if anybody could offer me a simple way to go about this. Do I need to create another method or just adjust the display river method?
public static void displayRiver(int[] river, boolean showShip) {
System.out.println();
System.out.print("|");
for (int val : river) {
switch (val) {
case -1: // No Ship
System.out.print("x");
break;
case 0: // Unknown
System.out.print(" ");
break;
case 1: // Ship Found
System.out.print(showShip ? "Y" : " ");
break;
}//switch
System.out.print("|");
}//for
System.out.println();
System.out.println();
}//displayRiver
// main method
public static void main(String[] arg) {
int riverLength = promptForInt("Please, enter the river lenght");
int [] shipArray = new int[riverLength];
int randomBattleshipLocation = new Random().nextInt(riverLength);
shipArray[randomBattleshipLocation] = 1;
boolean showShip = false ;
int userGuess;
do
{
displayRiver (shipArray, false);
userGuess = promptForInt(String.format("Guess, enter a location from 1 to " + riverLength));
userGuess = userGuess -1;
if(shipArray[userGuess] == 1)
{
System.out.println("Boom! ");
showShip = true;
displayRiver(shipArray, true);
}
else if(shipArray[userGuess] == -1)
{
System.out.println("Location was already hit, try again! ");
}
else if(shipArray[userGuess] == 0)
{
System.out.println("Splash...");
shipArray[userGuess] = -1 ;
}
} while(!showShip);
System.exit(0);
}
}
Your logic seems to be that an 1 in the array indicates a ship, and your ships apparently are never more than one in width.
You currently use the following to create one ship
int randomBattleshipLocation = new Random().nextInt(riverLength);
shipArray[randomBattleshipLocation] = 1;
So you could turn that into a method that creates a battleship, then call that as many times as you want for multiple ships. Just make sure that you don't assign a ship on top of another ship, or make another logical error (like trying to put 5 ships into a river of size 4, and it will loop forever trying to find space for ships).
Pseudo-code and not-so-pseudo-code:
for(int i = 0;i < shipsToAdd; i++) {
addShip(shipArray);
}
// Use a shared class-level Random object, don't do new Random().nextInt();
private static Random rnd = new Random();
private static addShip(int[] array) {
// Here you should loop to check if the array is already full of ships
// otherwise it's a design flaw that will result in an infinite loop with bad input
// loop until we find a shipless array index
int index = rnd.nextInt(array);
while(array[index] == 1)
index = rnd.nextInt(array);
array[index] = 1;
}

Hangman Game Not Reading From File

This program is supposed to pick a random word from a .txt file and have the user try and guess the letters to the word. It runs, but it always says "letter was not found in word" even when I know it's a letter that all of the words have. This makes me think that it isn't properly reading my .txt file.
package hangman;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class Hangman{
public static void main(String[] args) {
ArrayList<String> dictionaryList = new ArrayList<>();
File file = new File("src/hangman.txt");
try {
try (Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
dictionaryList.add(line);
}
}
} catch (FileNotFoundException e) {
}
/*
* Getting the word and hiding it
*/
Random rng = new Random();
int word = rng.nextInt(dictionaryList.size()); //randomly chooses a word from the text file
Scanner scanner = new Scanner(System.in);
int guessesLeft = 6; // the total amount of guesses the user gets
ArrayList<Character> alreadyGuess = new ArrayList<>(); // keep tracks of the user's guesses
boolean wordFound = false; // keeps track of when the game will end after the user runs out of guesses
String wordSelected = dictionaryList.get(word); //converts the int value of the randomly choose word to a string
char[] letters = wordSelected.toCharArray(); // converts the word to a char
char[] hideWord = new char[letters.length]; // gets the length of hiding the word
// the for loop hides the word by replacing it with '_'
for(int i = 0; i < letters.length; i++) {
hideWord[i]='_';
}
/*
* Starts the hangman game. The while loop will keep running the game.
*/
while(true){
//for testing purposes they can use the print statement below to replace the other print statement
//System.out.print("\n" + wordSelected + "\n" + "Word: ");
System.out.print("\n" + "Word: ");
for(int i = 0; i < letters.length; i++){
System.out.print(hideWord[i]);
} // Display the word
// Allows user to input and displays the guesses that are left
System.out.print("\n" + "Guesses Left: " + guessesLeft +"\nAlready Guess: " + alreadyGuess + "\nGuess: ");
char userInput = scanner.nextLine().toUpperCase().charAt(0); // uppercase the String first, and then pick the char
// Checks to see if the user already guess the same word
for(int i = 0; i < alreadyGuess.size(); i++){
if(userInput==alreadyGuess.get(i)){
System.out.println("\nYou already guessed this letter. Try Again. ");
break;
}
}
// records the user's guesses
if(!(alreadyGuess.contains(userInput))){
alreadyGuess.add(userInput);
}
// Checks if the user guesses the right letter in the word
for(int i = 0; i < letters.length; i++) {
if(userInput==letters[i]) {
hideWord[i] = userInput;
wordFound = true;
}
}
// If user guesses the incorrect letter it will display this and lower the amount of guesses
if(!wordFound){
System.out.println("\nThe letter was not found in the word. \n");
guessesLeft = 1;
}
wordFound = false; // resets the wordFound boolean back to false
// if user runs out of guesses left, they will lose.
if(guessesLeft<=0){
System.out.println("\nYou lose, you hanged the man.");
break;
}
// if user guesses correctly on the word, they win. Uses the array class to compare two char arrays
if(Arrays.equals(letters,hideWord)){
System.out.println("\nWord: " + wordSelected);
System.out.println("\nCongratulations! You guess the right word and save the man from being hang.");
break;
}
}
}
}
Never, ever, ever catch and ignore exceptions! Change the catch clause at the top of the program like this:
catch (FileNotFoundException e) {
e.printStackTrace();
}
so that you will at least have a hint if something bad happened while you were trying to read your word list.
This is such an important lesson it bears repeating, in bold type: Never, ever, ever catch and ignore exceptions!

null is returned when i try to print an array which logs userinput [Java]

I am trying to print an array which is populated by users input in a hangman game, but when printed it is returning [null,null,null,null,null,null].
Complete code
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Hangman {
public static void main(String[] args) {
Scanner consolereader= new Scanner(System.in); //Scanner
JOptionPane.showMessageDialog(null, "Welcome to Hangman");
Object[] options = {"Easy","Medium","Hard"};
int difficulty = JOptionPane.showOptionDialog(null,
"What difficulty would you like to "+ "play","A Question", //asking for what difficulty to play
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[2]);
switch(difficulty){ //switch that selects which difficulty
case 0: //case 0=easy
boolean endgame=false;
String[] easywords= new String[]{"integer","project","octopus"};
int lives = 12;
String[] lStorage= new String[12]; // array that stores the used letter bank
String easyrnd = (easywords[new Random().nextInt(easywords.length)]); // random word picker
String[] workingGuess= new String[easyrnd.length()];
for(int i=0;i<easyrnd.length(); i++)
{
workingGuess[i]=" _"; //making the lines
}
System.out.println(Arrays.toString(workingGuess)); //printing the lines
char[] chararray= easyrnd.toCharArray(); // making the word into char array
System.out.println("The word has " + easyrnd.length() + " Letters");
while(lives>0)
{ //the loop that controls game
System.out.println("\n Guess a letter");
String letterguess = consolereader.nextLine(); //reading their guess
char charletterguess = letterguess.charAt(0); // making their guess a chaar
if(easyrnd.contains(letterguess))
{ //if contains their guess then:
System.out.println("Correct ");
for(int i=12;i>0;i--){
lStorage[i]=letterguess;
}
for(int i=0;i<easyrnd.length(); i++)
{
if(chararray[i]==charletterguess) //checks where the letteer is in word
{
String charfound = Character.toString(charletterguess);
workingGuess[i]=charfound; //makes the line the letter they guessed if correct
}
}
for(int i =0;i<easyrnd.length();i++)
{
System.out.print(workingGuess[i]); //printing out the lines with any added letters
}
int count=0;
for(int i=0;i<easyrnd.length();i++)
{
if(workingGuess[i]=="_")
{ //the part we are stuck on!
count++;
}
}
} //closing what to do if guess is correct
else{
System.out.println("You have made a WRONG guess");
lives--; // subtracts a life
System.out.println("You have " + lives + " lives left on the hangman board ");
System.out.println(Arrays.toString(lStorage)); //need to display guessed words and pictures
}
if(lives==0)
{
System.out.println("sorry Game OVER"); //if out of lives game over
lives=0;
} //need to add PLAY AGain
}
break;
case 1:
String[] mediumwords= new String[]{"stereo","cyclone","element"};
String medrnd = (mediumwords[new Random().nextInt(mediumwords.length)]);
break;
case 2:
String[] hardwords= new String[]{"antidisestablishmentarianism","pessamistic","synonym"};
String hrdrnd = (hardwords[new Random().nextInt(hardwords.length)]);
break;
default:
System.out.println("you haven't chosen any");
break;
}
}
}
If the guess is correct then only
for(int i=12;i>0;i--){
lStorage[i]=letterguess;
}
this code will execute.. In else the IStorage array will be always null.
You are getting the null,null, .... because you are entering the else branch in
if(easyrnd.contains(letterguess))
If you guess the correct letter, you would get an "Invalid array range exception" here:
for(int i=12;i>0;i--){
lStorage[i]=letterguess;
}
Better:
for(int i=11;i>=0;i--){ //arrays start at 0 and finish at size-1
lStorage[i]=letterguess;
}
You have some other problems in your code:
First of all, you are initializing
workingGuess[i]=" _";
and checking for something else
workingGuess[i]=="_" // no space;
Compare with "equals":
if(" _".equals(workingGuess[i]){
}

Hangman code stuck on three different problems

I'm trying to make a hangman game. On each turn, the user guesses a letter. If they guessed correctly, they can guess again. Otherwise, their remaining available guesses drops by one, and the guessed letter is put into an array.
When the user hits zero remaining guesses, the program is supposed to ask if they want to play again. If they answer yes, it is supposed to restart the game, and if they answer no, the program ends.
The problem I'm having is with the array that holds the guesses, and with restarting the game.
Also, the program will error every once in a while when starting. The error is
Exception in thread "main" java.lang.NullPointerException at Hangman1.main(Hangman1.java:27)
The error when trying to restart the game is
Exception in thread "main" java.lang.NullPointerException at Hangman1.main(Hangman1.java:101)
searchArray is the method that is supposed to take the position of the char array and copy that in asterisk array and return asterisk array, that doesn't seem to work. Running debug it seems the problem that causes the program to crash is that word will sometimes end up null, but only sometimes and I don't really know why
import java.util.*;
import java.io.*;
public class Hangman1 {
static Scanner keyboard = new Scanner(System.in);
public static final int MAXSIZE = 15000;
public static final int NUM_GUESS = 8;
public static final int WORD_LENGTH = 20;
public static void main(String[] args) {
int random = pickrandom(MAXSIZE);
try {
// Set up connection to the input file
Scanner input = new Scanner(new FileReader("dictionary.txt"));
instructions();
keyboard.nextLine();
clearScreen();
String word = randomWord(input, random);
System.out.println(word);
String[] charArray = word.split("");
System.out.print("\n");
String[] asterisk = asteriskLine(word);
String decision = "Y";
//decision = keyboard.nextLine().toUpperCase();
System.out.println("Word to guess :");
for (int count = 0; count < word.length(); count++) {
System.out.print(asterisk[count]);
}
System.out.print("\n");
int tries = NUM_GUESS;
System.out.println("Enter a letter to guess or 9 to quit");
String guess = keyboard.next();
String[] wrongGuesses = new String [NUM_GUESS];
int guessMade = 0;
do {
//System.out.println(tries);
while (!(guess.equals("9")) && !(guess.equals(word)) && (tries > 0))
{
String letter = guess.substring(0,1);
if (word.indexOf(letter) < 0) {
clearScreen();
tries--;
wrongGuesses = wrongGuesses(guessMade, wrongGuesses, letter);
printArray(asterisk, charArray, word, tries, wrongGuesses, guessMade);
guessMade++;
guess = keyboard.next();
}
else {
clearScreen();
asterisk = searchArray(charArray, asterisk, guessMade, letter, word);
printArray(asterisk, charArray, word, tries, wrongGuesses, guessMade);
guess = keyboard.next();
}
if (charArray == asterisk) {
System.out.println("You won!");
}
if (tries == 0) {
System.out.println("You have no more guesses left");
}
}
if (guess.equals("9")) {
System.out.println("Thanks for playing");
}
System.out.println("Play again? Y/N");
decision = keyboard.next().toUpperCase();
if (decision.equals("Y")) {
random = pickrandom(MAXSIZE);
word = randomWord(input, random);
charArray = word.split("");
System.out.print("\n");
asterisk = asteriskLine(word);
guess = keyboard.next();
}
} while (decision.equals("Y"));
//System.out.println("Play again? Y/N");
//decision = keyboard.nextLine().toUpperCase();
}
catch (FileNotFoundException e) {
System.out.println("There was an error opening one of the files.");
}
}
//Clears screen after introduction
private static void clearScreen() {
for (int blanks = 0; blanks < 80; blanks++) {
System.out.println();
}
}
// This method returns a randomly selected integer
// between 0 and count-1
public static int pickrandom(int count) {
Random generator = new Random();
return generator.nextInt(count);
}
// Places asterisks in place of the letters in the word
// Parameter is the string word. it holds mystery word
public static String[] asteriskLine(String word) {
int i;
String[] asteriskArray = new String [word.length()];
for (i = 0; i < word.length(); i++) {
asteriskArray[i] = "* ";
}
return asteriskArray;
}
public static void instructions() {
System.out.println(" H A N G M A N. "
+ "\n This is a word guessing game. "
+ "\n A word will be selected at random and kept hidden. You will try to figure out the secret word by"
+ "\n guessing letters which you think are in the word. "
+ "\n You will guess one letter at a time. "
+ "\n If the letter you guess is correct, the position(s) of the letter in the secret word will be shown. "
+ "\n You will be allowed "
+ NUM_GUESS
+ " wrong guesses If you guess incorrectly "
+ NUM_GUESS
+ " times, you lose the game. "
+ "\n If you guess all of the letters in the word, you win."
+ "\n\n Press enter to continue ");
}
public static String randomWord(Scanner input, int random) {
String[] dictionaryWords = new String [MAXSIZE];
int usedsize = 0;
while (usedsize < MAXSIZE && input.hasNextLine()) {
dictionaryWords[usedsize] = input.nextLine();
usedsize++;
}
String word = dictionaryWords[random];
return word;
}
//Replaces correct guess in blanks
public static String correctWord(String guess, String word, String asterisk, char letter) {
return null;
}
public static void printArray(String[] asterisk, String[] charArray, String word, int tries, String[] wrongGuesses, int guessMade) {
System.out.println("Word to guess");
for (int count = 0; count < word.length(); count++) {
System.out.print(asterisk[count]);
}
System.out.println("\nGuesses remaining: " + tries);
System.out.print("Incorrect letters tried: ");
for (int count = 0; count <= guessMade; count++) {
System.out.print(wrongGuesses[count] + " ");
}
System.out.println("\nEnter a letter to guess or 9 to quit");
}
public static String[] wrongGuesses(int guessMade, String [] wrongGuesses, String letter) {
wrongGuesses[guessMade] = letter;
return wrongGuesses;
}
public static String[] searchArray(String[] charArray, String[] asterisk, int guessMade, String letter, String word) {
int[] a = new int[word.length()];
for (int count = 0; count < word.length(); count++) {
if (letter == charArray[count]) {
asterisk[count] = charArray[count];
}
}
return asterisk;
}
}
One thing that you need to do is to read all of your words in once and only once, and store them all into an ArrayList. Your current code tries to re-use a Scanner object that is already spent, and that will fail. Instead get your random word from the ArrayList<String>.
Running debug it seems the problem that causes the program to crash is
that word will sometimes end up null, but only sometimes and I don't
really know why
public static String randomWord(Scanner input, int random) {
String[] dictionaryWords = new String [MAXSIZE];
int usedsize = 0;
while (usedsize < MAXSIZE && input.hasNextLine()) {
dictionaryWords[usedsize] = input.nextLine();
usedsize++;
}
String word = dictionaryWords[random];
return word;
}
Sometimes random will be bigger than usedsize.
So you need to move this line from outside the loop
int random = pickrandom(MAXSIZE);
into this function, and have the maximum be usedsize (or usedsize-1).
You can protect yourself against this error, and work out whether you should be using usedsize or usedsize-1, by writing a unit test. Look into a Junit tutorial.
In your junit test, call randomword and pass it a very high value for random. Then
assert(word!= null)
Word is null when random is longer than the length of your dictionary.

Categories