Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- /*
- To play simply use .play() or just compile this in any java compiler (preferably eclipse)
- Feel free to change up the code if you want. Also feel free to view any other projects I made.
- */
- public class Hangman {
- private String word;
- private int lives;
- private String hint;
- public Hangman(String word,String hint) {
- this.word = word;
- this.hint = hint;
- this.lives = 6;
- }
- public Hangman() {
- this.word = "";
- this.hint = "";
- this.lives = 6;
- }
- public int getLives() {
- return this.lives;
- }
- public String getWord() {
- return this.word;
- }
- public void setWord(String s, String s2) {
- this.word = s;
- this.hint = s2;
- }
- public void play() {
- Scanner scan = new Scanner(System.in);
- if(getWord() == "") {
- System.out.println("Enter Word");
- String word = scan.nextLine();
- System.out.println("Enter Hint");
- String hint = scan.nextLine();
- setWord(word,hint);
- for(int i = 0; i < 1000; i++) {
- System.out.println();
- }
- }
- String[] wordArray = new String [getWord().length()];
- String[] toOutput = new String [getWord().length()];
- String output = "";
- for(int i = 0; i < word.length(); i++) {
- if(getWord().substring(i, i+1).toLowerCase().contains(" ")) {
- toOutput [i] = " ";
- wordArray[i] = " ";
- output+= " ";
- }else {
- toOutput [i] = "_";
- wordArray[i] = getWord().substring(i, i+1).toLowerCase();
- output += "_ ";
- }
- }
- while (output.contains("_") && getLives() > 0) {
- System.out.println(output);
- System.out.println(this.hint);
- System.out.println("Lives: " + this.lives);
- System.out.println("Input Letter");
- String guess = scan.next();
- guess = guess.toLowerCase();
- boolean correct = false;
- output = "";
- for(int i = 0; i < this.word.length(); i++) {
- if(wordArray[i].contains(guess)) {
- toOutput[i] = wordArray[i];
- correct = true;
- }
- output += toOutput[i] + " ";
- }
- System.out.println();
- if(correct == false) {
- this.lives--;
- }
- }
- if(lives != 0) {
- if (word != "") {
- System.out.println("You Won! The Word Was " + this.word);
- }else {
- System.out.println("You Won! The Word Wasn't Set");
- }
- }else {
- System.out.println("You Lost! The Word Was " + this.word);
- }
- scan.close();
- }
- public static void main(String[] args) {
- Hangman h = new Hangman();
- h.play();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement