A Simple HangMan Game Implemented in the Java LanguageComplete Hangman gameHangman game in JavaHangman game in Java - second tryVery simple Hangman gameSimple game of HangmanSimple Hangman gameSimple Hangman game in JavaSimple Python hangman gameSimple game - hangmanSimple CLI Python Hangman game

Is having access to past exams cheating and, if yes, could it be proven just by a good grade?

Fill color and outline color with the same value

Russian cases: A few examples, I'm really confused

Ban on all campaign finance?

How could a female member of a species produce eggs unto death?

Happy pi day, everyone!

Making a sword in the stone, in a medieval world without magic

Bash: What does "masking return values" mean?

SQL Server Primary Login Restrictions

Meaning of "SEVERA INDEOVI VAS" from 3rd Century slab

Check this translation of Amores 1.3.26

Good allowance savings plan?

What does it mean to make a bootable LiveUSB?

How to make healing in an exploration game interesting

Did CPM support custom hardware using device drivers?

Co-worker team leader wants to inject his friend's awful software into our development. What should I say to our common boss?

Make a transparent 448*448 image

How to explain that I do not want to visit a country due to personal safety concern?

Counting certain elements in lists

Identifying the interval from A♭ to D♯

What has been your most complicated TikZ drawing?

It's a yearly task, alright

Possible Leak In Concrete

What are the possible solutions of the given equation?



A Simple HangMan Game Implemented in the Java Language


Complete Hangman gameHangman game in JavaHangman game in Java - second tryVery simple Hangman gameSimple game of HangmanSimple Hangman gameSimple Hangman game in JavaSimple Python hangman gameSimple game - hangmanSimple CLI Python Hangman game













0












$begingroup$


This is my first post on this forum showing you a simple implementation of the HangMan game in Java. This is a side project and this deviated from the usual programs I write which are either school assignments or problems on coding websites.



It feels great to have something simple working, but I know for sure this can be improved. This only runs through the command line now, but I'm thinking of adding a lot more to this in the near future.
Thanks.



import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main


public static void main(String[] args) throws FileNotFoundException

Scanner userGuess = new Scanner(System.in);

printTitleScreen();
System.out.println("");
String word = getRandomWordFromFile("/Users/kingcold/Desktop/words.txt");
char[] wordCharArray = word.toCharArray();

System.out.println("It's time to guess the word!");

StringBuilder gameWord = new StringBuilder(printBlankSpaces(word));

int successfulAttempts = 0;
int failedAttempts = 0;
int totalAttempts = 0;


do

System.out.println("Your word looks like this: " + gameWord);
System.out.println("Your guess: ");

String userInput = userGuess.next();
char charUserInput = userInput.charAt(0);

if (isValidInput(userInput))
System.out.println("Your guess is: " + userInput);

if (!(containsUserInput(wordCharArray, userInput)))

letterNotInWordMessage(userInput);
failedAttempts++;

else if (containsUserInput(wordCharArray, userInput))

letterInWordMessage(userInput);
gameWord.setCharAt(getMatchingIndex(wordCharArray, userInput), charUserInput);
successfulAttempts++;



else

System.out.println("Invalid input entered. Try again.");



totalAttempts = successfulAttempts + failedAttempts;


while (!word.equals(gameWord.toString()));


if (word.equals(gameWord.toString()))
System.out.println("Congratulations, you correctly guessed the word!");
System.out.println("The word is " + word);
System.out.println("You guessed the word in " + totalAttempts + " attempts");
userGuess.close();




private static void printTitleScreen()
System.out.println("-------------------");
System.out.println("Welcome to Hangman!");
System.out.println("-------------------");


private static String printBlankSpaces(String word)
return new String(new char[word.length()]).replace('', '-');


private static void letterNotInWordMessage(String letter)
System.out.println("The letter " + letter + " is not in the word!");


private static void letterInWordMessage(String letter)
System.out.println("The letter " + letter + " is in the word!");


private static int getMatchingIndex(char[] wordArray, String userGuess)
int index = -1;
for (int i = 0; i < wordArray.length && (index == -1); i++)
if (String.valueOf(wordArray[i]).equals(userGuess))
index = i;


return index;


private static boolean containsUserInput(char[] wordArray, String userGuess)
for (int i = 0; i < wordArray.length; i++)
if (wordArray[i] == userGuess.charAt(0))
return true;


return false;


private static boolean isValidInput(String userGuess)
final int VALID_INPUT_LENGTH = 1;
if (userGuess.length() == VALID_INPUT_LENGTH && Character.isLetter(userGuess.charAt(0)))
return true;

return false;


private static String getRandomWordFromFile(String fileName) throws FileNotFoundException

File file = new File(fileName);
Scanner fileScanner = new Scanner(file);
String fileContents = "";

while(fileScanner.hasNextLine())
fileContents = fileContents.concat(fileScanner.nextLine() + "n");


fileScanner.close();
String[] fileContentArray = fileContents.split("n");
return fileContentArray[(int) (Math.random() * fileContentArray.length)];













share







New contributor




King Cold is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$
















    0












    $begingroup$


    This is my first post on this forum showing you a simple implementation of the HangMan game in Java. This is a side project and this deviated from the usual programs I write which are either school assignments or problems on coding websites.



    It feels great to have something simple working, but I know for sure this can be improved. This only runs through the command line now, but I'm thinking of adding a lot more to this in the near future.
    Thanks.



    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;

    public class Main


    public static void main(String[] args) throws FileNotFoundException

    Scanner userGuess = new Scanner(System.in);

    printTitleScreen();
    System.out.println("");
    String word = getRandomWordFromFile("/Users/kingcold/Desktop/words.txt");
    char[] wordCharArray = word.toCharArray();

    System.out.println("It's time to guess the word!");

    StringBuilder gameWord = new StringBuilder(printBlankSpaces(word));

    int successfulAttempts = 0;
    int failedAttempts = 0;
    int totalAttempts = 0;


    do

    System.out.println("Your word looks like this: " + gameWord);
    System.out.println("Your guess: ");

    String userInput = userGuess.next();
    char charUserInput = userInput.charAt(0);

    if (isValidInput(userInput))
    System.out.println("Your guess is: " + userInput);

    if (!(containsUserInput(wordCharArray, userInput)))

    letterNotInWordMessage(userInput);
    failedAttempts++;

    else if (containsUserInput(wordCharArray, userInput))

    letterInWordMessage(userInput);
    gameWord.setCharAt(getMatchingIndex(wordCharArray, userInput), charUserInput);
    successfulAttempts++;



    else

    System.out.println("Invalid input entered. Try again.");



    totalAttempts = successfulAttempts + failedAttempts;


    while (!word.equals(gameWord.toString()));


    if (word.equals(gameWord.toString()))
    System.out.println("Congratulations, you correctly guessed the word!");
    System.out.println("The word is " + word);
    System.out.println("You guessed the word in " + totalAttempts + " attempts");
    userGuess.close();




    private static void printTitleScreen()
    System.out.println("-------------------");
    System.out.println("Welcome to Hangman!");
    System.out.println("-------------------");


    private static String printBlankSpaces(String word)
    return new String(new char[word.length()]).replace('', '-');


    private static void letterNotInWordMessage(String letter)
    System.out.println("The letter " + letter + " is not in the word!");


    private static void letterInWordMessage(String letter)
    System.out.println("The letter " + letter + " is in the word!");


    private static int getMatchingIndex(char[] wordArray, String userGuess)
    int index = -1;
    for (int i = 0; i < wordArray.length && (index == -1); i++)
    if (String.valueOf(wordArray[i]).equals(userGuess))
    index = i;


    return index;


    private static boolean containsUserInput(char[] wordArray, String userGuess)
    for (int i = 0; i < wordArray.length; i++)
    if (wordArray[i] == userGuess.charAt(0))
    return true;


    return false;


    private static boolean isValidInput(String userGuess)
    final int VALID_INPUT_LENGTH = 1;
    if (userGuess.length() == VALID_INPUT_LENGTH && Character.isLetter(userGuess.charAt(0)))
    return true;

    return false;


    private static String getRandomWordFromFile(String fileName) throws FileNotFoundException

    File file = new File(fileName);
    Scanner fileScanner = new Scanner(file);
    String fileContents = "";

    while(fileScanner.hasNextLine())
    fileContents = fileContents.concat(fileScanner.nextLine() + "n");


    fileScanner.close();
    String[] fileContentArray = fileContents.split("n");
    return fileContentArray[(int) (Math.random() * fileContentArray.length)];













    share







    New contributor




    King Cold is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.







    $endgroup$














      0












      0








      0





      $begingroup$


      This is my first post on this forum showing you a simple implementation of the HangMan game in Java. This is a side project and this deviated from the usual programs I write which are either school assignments or problems on coding websites.



      It feels great to have something simple working, but I know for sure this can be improved. This only runs through the command line now, but I'm thinking of adding a lot more to this in the near future.
      Thanks.



      import java.io.File;
      import java.io.FileNotFoundException;
      import java.util.Scanner;

      public class Main


      public static void main(String[] args) throws FileNotFoundException

      Scanner userGuess = new Scanner(System.in);

      printTitleScreen();
      System.out.println("");
      String word = getRandomWordFromFile("/Users/kingcold/Desktop/words.txt");
      char[] wordCharArray = word.toCharArray();

      System.out.println("It's time to guess the word!");

      StringBuilder gameWord = new StringBuilder(printBlankSpaces(word));

      int successfulAttempts = 0;
      int failedAttempts = 0;
      int totalAttempts = 0;


      do

      System.out.println("Your word looks like this: " + gameWord);
      System.out.println("Your guess: ");

      String userInput = userGuess.next();
      char charUserInput = userInput.charAt(0);

      if (isValidInput(userInput))
      System.out.println("Your guess is: " + userInput);

      if (!(containsUserInput(wordCharArray, userInput)))

      letterNotInWordMessage(userInput);
      failedAttempts++;

      else if (containsUserInput(wordCharArray, userInput))

      letterInWordMessage(userInput);
      gameWord.setCharAt(getMatchingIndex(wordCharArray, userInput), charUserInput);
      successfulAttempts++;



      else

      System.out.println("Invalid input entered. Try again.");



      totalAttempts = successfulAttempts + failedAttempts;


      while (!word.equals(gameWord.toString()));


      if (word.equals(gameWord.toString()))
      System.out.println("Congratulations, you correctly guessed the word!");
      System.out.println("The word is " + word);
      System.out.println("You guessed the word in " + totalAttempts + " attempts");
      userGuess.close();




      private static void printTitleScreen()
      System.out.println("-------------------");
      System.out.println("Welcome to Hangman!");
      System.out.println("-------------------");


      private static String printBlankSpaces(String word)
      return new String(new char[word.length()]).replace('', '-');


      private static void letterNotInWordMessage(String letter)
      System.out.println("The letter " + letter + " is not in the word!");


      private static void letterInWordMessage(String letter)
      System.out.println("The letter " + letter + " is in the word!");


      private static int getMatchingIndex(char[] wordArray, String userGuess)
      int index = -1;
      for (int i = 0; i < wordArray.length && (index == -1); i++)
      if (String.valueOf(wordArray[i]).equals(userGuess))
      index = i;


      return index;


      private static boolean containsUserInput(char[] wordArray, String userGuess)
      for (int i = 0; i < wordArray.length; i++)
      if (wordArray[i] == userGuess.charAt(0))
      return true;


      return false;


      private static boolean isValidInput(String userGuess)
      final int VALID_INPUT_LENGTH = 1;
      if (userGuess.length() == VALID_INPUT_LENGTH && Character.isLetter(userGuess.charAt(0)))
      return true;

      return false;


      private static String getRandomWordFromFile(String fileName) throws FileNotFoundException

      File file = new File(fileName);
      Scanner fileScanner = new Scanner(file);
      String fileContents = "";

      while(fileScanner.hasNextLine())
      fileContents = fileContents.concat(fileScanner.nextLine() + "n");


      fileScanner.close();
      String[] fileContentArray = fileContents.split("n");
      return fileContentArray[(int) (Math.random() * fileContentArray.length)];













      share







      New contributor




      King Cold is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.







      $endgroup$




      This is my first post on this forum showing you a simple implementation of the HangMan game in Java. This is a side project and this deviated from the usual programs I write which are either school assignments or problems on coding websites.



      It feels great to have something simple working, but I know for sure this can be improved. This only runs through the command line now, but I'm thinking of adding a lot more to this in the near future.
      Thanks.



      import java.io.File;
      import java.io.FileNotFoundException;
      import java.util.Scanner;

      public class Main


      public static void main(String[] args) throws FileNotFoundException

      Scanner userGuess = new Scanner(System.in);

      printTitleScreen();
      System.out.println("");
      String word = getRandomWordFromFile("/Users/kingcold/Desktop/words.txt");
      char[] wordCharArray = word.toCharArray();

      System.out.println("It's time to guess the word!");

      StringBuilder gameWord = new StringBuilder(printBlankSpaces(word));

      int successfulAttempts = 0;
      int failedAttempts = 0;
      int totalAttempts = 0;


      do

      System.out.println("Your word looks like this: " + gameWord);
      System.out.println("Your guess: ");

      String userInput = userGuess.next();
      char charUserInput = userInput.charAt(0);

      if (isValidInput(userInput))
      System.out.println("Your guess is: " + userInput);

      if (!(containsUserInput(wordCharArray, userInput)))

      letterNotInWordMessage(userInput);
      failedAttempts++;

      else if (containsUserInput(wordCharArray, userInput))

      letterInWordMessage(userInput);
      gameWord.setCharAt(getMatchingIndex(wordCharArray, userInput), charUserInput);
      successfulAttempts++;



      else

      System.out.println("Invalid input entered. Try again.");



      totalAttempts = successfulAttempts + failedAttempts;


      while (!word.equals(gameWord.toString()));


      if (word.equals(gameWord.toString()))
      System.out.println("Congratulations, you correctly guessed the word!");
      System.out.println("The word is " + word);
      System.out.println("You guessed the word in " + totalAttempts + " attempts");
      userGuess.close();




      private static void printTitleScreen()
      System.out.println("-------------------");
      System.out.println("Welcome to Hangman!");
      System.out.println("-------------------");


      private static String printBlankSpaces(String word)
      return new String(new char[word.length()]).replace('', '-');


      private static void letterNotInWordMessage(String letter)
      System.out.println("The letter " + letter + " is not in the word!");


      private static void letterInWordMessage(String letter)
      System.out.println("The letter " + letter + " is in the word!");


      private static int getMatchingIndex(char[] wordArray, String userGuess)
      int index = -1;
      for (int i = 0; i < wordArray.length && (index == -1); i++)
      if (String.valueOf(wordArray[i]).equals(userGuess))
      index = i;


      return index;


      private static boolean containsUserInput(char[] wordArray, String userGuess)
      for (int i = 0; i < wordArray.length; i++)
      if (wordArray[i] == userGuess.charAt(0))
      return true;


      return false;


      private static boolean isValidInput(String userGuess)
      final int VALID_INPUT_LENGTH = 1;
      if (userGuess.length() == VALID_INPUT_LENGTH && Character.isLetter(userGuess.charAt(0)))
      return true;

      return false;


      private static String getRandomWordFromFile(String fileName) throws FileNotFoundException

      File file = new File(fileName);
      Scanner fileScanner = new Scanner(file);
      String fileContents = "";

      while(fileScanner.hasNextLine())
      fileContents = fileContents.concat(fileScanner.nextLine() + "n");


      fileScanner.close();
      String[] fileContentArray = fileContents.split("n");
      return fileContentArray[(int) (Math.random() * fileContentArray.length)];











      java game





      share







      New contributor




      King Cold is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.










      share







      New contributor




      King Cold is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.








      share



      share






      New contributor




      King Cold is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 5 mins ago









      King ColdKing Cold

      1




      1




      New contributor




      King Cold is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      King Cold is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      King Cold is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.




















          0






          active

          oldest

          votes











          Your Answer





          StackExchange.ifUsing("editor", function ()
          return StackExchange.using("mathjaxEditing", function ()
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          );
          );
          , "mathjax-editing");

          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "196"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );






          King Cold is a new contributor. Be nice, and check out our Code of Conduct.









          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f215463%2fa-simple-hangman-game-implemented-in-the-java-language%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          King Cold is a new contributor. Be nice, and check out our Code of Conduct.









          draft saved

          draft discarded


















          King Cold is a new contributor. Be nice, and check out our Code of Conduct.












          King Cold is a new contributor. Be nice, and check out our Code of Conduct.











          King Cold is a new contributor. Be nice, and check out our Code of Conduct.














          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f215463%2fa-simple-hangman-game-implemented-in-the-java-language%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          कुँवर स्रोत दिक्चालन सूची"कुँवर""राणा कुँवरके वंशावली"

          Why is a white electrical wire connected to 2 black wires?How to wire a light fixture with 3 white wires in box?How should I wire a ceiling fan when there's only three wires in the box?Two white, two black, two ground, and red wire in ceiling box connected to switchWhy is there a white wire connected to multiple black wires in my light box?How to wire a light with two white wires and one black wireReplace light switch connected to a power outlet with dimmer - two black wires to one black and redHow to wire a light with multiple black/white/green wires from the ceiling?Ceiling box has 2 black and white wires but fan/ light only has 1 of eachWhy neutral wire connected to load wire?Switch with 2 black, 2 white, 2 ground and 1 red wire connected to ceiling light and a receptacle?

          चैत्य भूमि चित्र दीर्घा सन्दर्भ बाहरी कडियाँ दिक्चालन सूची"Chaitya Bhoomi""Chaitya Bhoomi: Statue of Equality in India""Dadar Chaitya Bhoomi: Statue of Equality in India""Ambedkar memorial: Centre okays transfer of Indu Mill land"चैत्यभमि