SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Arrays
Exercise:
Programming Projects
Question:2 | ISBN:9780136091813 | Edition: 2

Question

Write a game of Hangman using arrays. Allow the user to guess letters and represent which letters have been guessed in an array.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

import java.util.Scanner;
public class TestDemo 
{
public static void main(String[] args) 
{
		Scanner input=new Scanner(System.in);
		String word="TRUMP";
		char[] key={'T','R','U','M','P'};
		char ch='-';
		String keyChar;
		int len;
		int pos;
		int st=0;
		len=word.length();
		int count=0;
		for(int i=0;i<key.length;i++)
			key[i]='-';
		
		do
		{
			System.out.print("Enter your guess:");
			keyChar=input.next();
			ch=keyChar.charAt(0);
			do
			{
				boolean res=check(word, ch, st, len);
				if(res==true)
					count++;
				pos=getPosition(word, ch, st, len);
				if(pos==-1)
					break;
				key[pos]=ch;
				st=pos+1;
			}while(st<len);
			st=0;
			pos=0;
			display(key, len);
			
		}while(count!=len);
System.out.println("Correct word guessed..! Congratulations :)");
	}
public static boolean check(String word,char ch,
    int st,int len)
	{
		for(int i=st;i<len;i++)
		{
			if(word.charAt(i)==ch)
				return true;
		}
		return false;
	}
	public static int getPosition(String word,char ch,int st,int len)
	{
		for(int i=st;i<len;i++)
	 		if(word.charAt(i)==ch)
			{
				return i;
			}
		return -1;
	}
	public static void display(char[] key,int len)
	{
		System.out.print(key);
		System.out.println();
	}
}

OUTPUT:

Enter your guess:M
---M-
Enter your guess:P
---MP
Enter your guess:T
T--MP
Enter your guess:U
T-UMP
Enter your guess:R
TRUMP
Correct word guessed..! Congratulations :)

 

0 0

Discussions

Post the discussion to improve the above solution.