Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Created by Cody Smith
- //This program used a static approach to create hangman
- package hangman;
- import java.util.*;
- public class static_approach
- {
- static Scanner keyboard = new Scanner(System.in);
- static Random rand = new Random();
- static boolean isIn(char c, String str)
- {
- for (int i=0; i<str.length(); i++) {
- if (str.substring(i, i+1).equals("c"));
- }
- return true;
- }
- static boolean printCurrStatus(String strToGuess, String userInputs)
- {
- int i, p=0;
- char letter;
- char strLetter;
- letter = '-';
- char [] carray = new char[10];
- for (i = 0; i < strToGuess.length(); i++)
- {
- carray[i]='-';
- System.out.print(carray[i]);
- }
- do
- {
- System.out.println("");
- System.out.println("Current Status for userInputs= " + userInputs );
- System.out.println("Enter next letter:");
- Scanner in = new Scanner (System.in);
- String strCh= in.nextLine();
- strCh = strCh.trim();
- userInputs+=strCh;
- // Check if letter already have been entered by user before
- for (i = 0; i < strToGuess.length(); i++) {
- if (strCh.length() != 0)
- letter = strCh.charAt(0);
- strLetter = strToGuess.charAt(i);
- if (isIn(letter, strToGuess))
- if(letter== strLetter)
- {
- carray[i]= letter;
- p +=1;
- }
- }
- for (i=0; i < strToGuess.length();i++)
- System.out.print(carray[i]);
- } while (p < strToGuess.length() );
- System.out.println("");
- System.out.println("Current Status for userInputs= " + userInputs );
- //System.out.println(" P " + p + " len " + strToGuess.length());
- return true;
- }
- static String getNextWordToGuess()
- {
- final int num_words=10; // change this if you have a different number of words
- int num = rand.nextInt(num_words);
- // Another way to accomplish the same thing:
- // int num = (int)(num_words* Math.random());
- List<String> my_words = new LinkedList<String>();
- my_words.add("elephant");
- my_words.add("tiger");
- my_words.add("monkey");
- my_words.add("baboon");
- my_words.add("barbeque");
- my_words.add("giraffe");
- my_words.add("simple");
- my_words.add("zebra");
- my_words.add("porcupine");
- my_words.add("aardvark");
- Random rg = new Random();
- String randomElement="";
- int listSize = my_words.size();
- //while(listSize <= 10) {
- randomElement = my_words.get(rg.nextInt(listSize));
- System.out.println("Word is : "+ randomElement);
- // Thread.sleep(SLEEP_TIME)
- //}
- return randomElement;
- }
- static void playGame()
- {
- String strToGuess = getNextWordToGuess();
- String userInputs="";
- printCurrStatus(strToGuess, userInputs);
- }
- public static void main(String[] args)
- {
- String response="";
- do
- {
- playGame();
- System.out.print("Do you want to play static approach Hangman again? (y or n): ");
- response = keyboard.next();
- } while (response.charAt(0) == 'y');
- System.out.println("Bye!");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement