Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Zusatzaufgaben;
- import java.util.Scanner;
- public class Zusatzaufgabe1_Hangman {
- public static String copyToWord(char[] copy) {
- StringBuilder builder = new StringBuilder();
- for (int i = 0; i < copy.length; i++) {
- builder.append(copy[i]);
- }
- return builder.toString();
- }
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- final String[] secretWords = {"Giraffe", "Neck", "Password", "Rating", "Food", "Übung", "Gitlab"};
- final String secretWord = secretWords[(int) (Math.random() * secretWords.length)].toUpperCase();
- final char[] copy = secretWord.toCharArray();
- for (int i = 0; i < copy.length; i++) {
- copy[i] = '_';
- }
- char currentChar;
- int currentCharNumber = 0;
- int tries = 0;
- int maximumtries = 10;
- System.out.println("Welcome to Hangman! To progress in the game you need to enter letters. Your word will look something like this:\n");
- while (!copyToWord(copy).equals(secretWord) && tries < maximumtries) {
- for(int i = 0; i < copy.length; i++) {
- System.out.print(copy[i]+ " ");
- }
- System.out.println("\nEnter your next character! You have " + (maximumtries-tries) + " tries left!");
- currentChar = scanner.next().charAt(0);
- if(Character.toUpperCase(currentChar) == secretWord.charAt(currentCharNumber)) {
- System.out.println("Hooray! Thats the correct character. Good job!\n");
- copy[currentCharNumber] = currentChar;
- currentCharNumber++;
- } else {
- if(tries+1 < maximumtries)
- System.out.println("You entered the wrong character. Try again!\n");
- tries++;
- continue;
- }
- tries++;
- }
- if(copyToWord(copy).equals(secretWord))
- System.out.println("Thanks for playing! You beat the game in " + tries + " tries.");
- else
- System.out.println("You didnt beat the game. Better luck next time.");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement