- import java.util.Scanner;
- public class hangman1 {
- //A method to create a substring, in order to show the correct letters such as "Me***n" for the word "Merlin".
- public static String replaceCharAt(String s, int pos, char c) {
- return s.substring(0,pos) + c + s.substring(pos+1);
- }
- public static void main(String[] args) {
- Scanner input = new Scanner(System.in);
- String word = "";
- String display = "";
- String guess = "";
- int wordLen=0;
- int guessLen=0;
- boolean correct = false;
- boolean win = false;
- //Generating a random number between 1-7
- int randomNumber=((int)(Math.random()*7+1));
- switch (randomNumber) {
- case 1 : word = "Merlin";
- case 2 : word = "Dexter";
- case 3 : word = "The Closer";
- case 4 : word = "House";
- case 5 : word = "Friends";
- case 6 : word = "Survivor";
- case 7 : word = "Simpsons";
- }
- //A for loop for counting the attempts
- for (int attempt=9; attempt!=0; attempt--){
- //Making sure that the user entered only one letter
- do{
- System.out.println("Please enter a letter: ");
- guess = input.next();
- if (guess.length()>1)
- System.out.println("You have to enter a letter not a word.");
- }while(guess.length()!=1);
- wordLen=word.length();
- for(int a=1; a!=wordLen; a++)
- display+="*";
- //Another for loop to check every letter in the "word", using the replaceCharAt method created at the top.
- for(int i = 0; i!=(wordLen-1); i++){
- if (guess.charAt(0)==word.charAt(i)){
- replaceCharAt(display,i, word.charAt(i));
- attempt++; //So the user dont lose a attempt point when their guess was correct.
- correct = true;
- }
- }
- if (correct){
- System.out.println("You found a letter!");
- System.out.println(display);}
- else {
- System.out.println("Your guess was wrong. " + attempt + " attemps left");
- System.out.println(display);}
- }
- }
- }