Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

The following is for a computer science program using Dr.Java. Prompt: Creating

ID: 3678519 • Letter: T

Question

The following is for a computer science program using Dr.Java.

Prompt: Creating a simple game of hangman. Write a program to ask a user to enter a word, storing each character of the string into an array. Add enough line breaks to get the string off the screen. Set up a second character array the same length as the first and fill with '_' characters. Use this second array to present to another user, allowing them to guess letters. As they guess a letter that is in the original word, fill it in in the second array and re-display. If they guess a letter that is not in the word, take away a "try". Give them 6 tries to guess the whole word or they lose.

Explanation / Answer

import java.util.Scanner;

public class Hangama {
  
   public static Scanner sc = new Scanner(System.in);
  
   public static void fillArray(char[] guess){
       for(int i=0; i<guess.length; i++)
           guess[i] = '_';
   }
  
   public static void print(char[] arr){
       for(int i=0; i<arr.length;i++)
           System.out.print(arr[i]);
       System.out.println();
   }

   public static boolean game(char answer[], char guess[])
   {
        int x = 0;
        char letter;

        print(guess);
        while (x < answer.length)
        {
           letter = sc.next().charAt(0);
            if (letter == answer[x])
            {
                guess[x]= letter;
               print(guess);
            }
            else
            {
               System.out.println("try..");
                return false;
            }    

            ++x;
        }
        return true;
   }
  
   public static void main(String[] args) {
      
       int i=1;
       System.out.print("Enter a word: ");
       char[] word = sc.next().toCharArray();
       char[] guess = new char[word.length];
      
       boolean flag = false;
      
       while(!flag && i<=6){
           fillArray(guess);
           flag = game(word, guess);
       }
       if(flag)
           System.out.println("You won!!");
       else
           System.out.println("You loosed!!!");
      
   }
}


/*

Output:

Enter a word: apple
_____
a
a____
p
ap___
p
app__
k
try..
_____
a
a____
p
ap___
p
app__
l
appl_
e
apple
You won!!

*/